Hi,
I am trying to learn the concept of fork, thus I wrote a program to test my knowledge, I will appreicate if anyone can point out what am I doing wrong with this codes. Thank you !
Freddie
Code:#include <stdio.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> // fork() -1 no process is created, original goes on running // fork(), The child returns 0 // fork(), parent returns positive PID of the child int main(int argc,char **argv) { pid_t child, parent, old_ppid, new_ppid; printf(" Current PID is %d\n", parent = getpid()); printf(" Current process PPID %d\n ", old_ppid = getppid()); if (( child = fork() ) < 0 ) /* handle error */ fprintf(stderr, " %s Fork failed! %s", argv[0], strerror(errno)); exit(1); else if (child == 0 ) { //fork succesful { sleep(3); //if it is a process , sleep for one second printf("This is the new process\n"); printf("It PID as %d \n",getpid()); printf("Parent PID as %d\n", getppid() ); exit(0); } else{ sleep(1); //if it is a parent , sleep for 2 seconds printf("This is the parent process\n"); printf("Parent PID as %d \n", getppid( )); exit(0);} return 0; }



LinkBack URL
About LinkBacks


