hi everyone;
i want to create 2 prrocesses with fork command and first child will print the number from 0 to 9 with 1 second delay (and then will exit) and the other child will write the same number simultaneously to a file (and then will terminate). The parent process will be waiting for one child to exit and print something basically.
Here is my code.
i did not understand how to kill a specific process. i used a cathc_child function but it was a sample code(i did not write it) so i did not understand how this function works either.Code:#include <unistd.h> /* defines fork() */ #include <sys/wait.h> /* defines the wait() system call. */ #include <sys/types.h> /*defines pid_t */ #include <stdio.h> void catch_child(int sig_num) { /* when we get here, we know there's a zombie child waiting */ int child_status; wait(&child_status); printf("child exited.\n"); } int main(int argc, char* argv[]) { FILE *fp; pid_t child_pid; pid_t child_pid2; //int child_status; int i; fp = fopen("labwork2.txt","w"); child_pid = fork(); signal(SIGCHLD, catch_child); switch(child_pid) { case -1: /* fork() failed */ perror("fork"); /* print a system-defined error message */ exit(1); case 0: /* fork() succeeded, we're inside the child process */ for(i = 0; i < 10; i++) { fprintf(fp,"%d\n",i); fflush(fp); sleep(1); } fclose(fp); //waitpid(child_pid,0,0); exit(0); default: child_pid2 = fork(); if(child_pid2 == 0) { execl("/usr/bin/tail","tail","-f","file.txt",(char*)0); } else if(child_pid2 > 0) { printf("Kill all\n"); } } }
when i compile and run the code, at the first time it prints the number both to the screen and to the file but if i run it again it starts printing number twice or more.



LinkBack URL
About LinkBacks


