Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/wait.h>
- int main(int argc, char **argv){
- //printf("0: %s \n", argv[0]);
- //printf("start pid: %d arg: %s\n", getpid(), argv[1]);
- //pierwszy arg - nazwa uruchamianego pliku
- if (argc > 2 || argc == 1 || strlen(argv[1]) > 20) {
- fprintf (stderr, "Blad argumentow");
- exit(1);
- }
- if (strlen(argv[1]) == 1) {
- exit(argv[1][0]);
- //return argv[1][0];
- //printf("%d", argv[1][0]);
- }
- else {
- int dlugosc = strlen(argv[1]);
- int polowa = dlugosc/2;
- char *pierwszaPolowa = malloc(sizeof(char) * polowa);
- char *drugaPolowa;
- if (dlugosc % 2 == 0) {
- drugaPolowa = malloc(sizeof(char) * polowa);
- } else {
- drugaPolowa = malloc(sizeof(char) * polowa+1);
- }
- for (int i =0; i< polowa ; i++ ) {
- pierwszaPolowa[i] = argv[1][i];
- }
- int index = 0;
- for (int i = polowa; i<dlugosc; i++){
- drugaPolowa[index] = argv[1][i];
- index++;
- }
- int child1pid=fork();
- int child2pid;
- if (child1pid == 0) {
- //execl - pierwszy argument - sciezka do pliku, drugi - pierwszy(zerowy) argument programu, ktory ma zostac uruchiomiony
- execl(argv[0], argv[0], pierwszaPolowa, NULL);
- }
- if (child1pid > 0) { //parent
- child2pid = fork();
- if (child2pid == 0 ) {
- execl(argv[0], argv[0], drugaPolowa, NULL);
- }
- }
- int status, status2;
- int pid1 = wait(&status);
- printf("wynik: %d %d %s %c\n", getpid(), pid1, pid1 == child1pid ? pierwszaPolowa : drugaPolowa, WEXITSTATUS(status));
- int pid2= wait(&status2);
- printf("wynik: %d %d %s %c\n", getpid(), pid2, pid2 == child2pid ? drugaPolowa : pierwszaPolowa, WEXITSTATUS(status2));
- free(pierwszaPolowa);
- free(drugaPolowa);
- //konczy program, zwraca wiekszy z kodow powrotu otrzymanych od dzieci
- exit(WEXITSTATUS(status) > WEXITSTATUS(status2) ? WEXITSTATUS(status) : WEXITSTATUS(status2));
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement