fork(3) download
  1. /* main program illustrating the UNIX fork() system call.
  2. Compile using cc -o main main.c
  3. */
  4. #include <stdio.h>
  5. main() {
  6. int fork(), childpid, value;
  7.  
  8. childpid = fork(); /* create a new process */
  9.  
  10. if(childpid == -1) {
  11. perror("can’t fork. Help!!");
  12. exit(-1);
  13. }
  14.  
  15. else if(childpid == 0) { /* child process */
  16. printf("child: my_process_id= %d,parent_process_id=%d\n", getpid(), getppid());
  17. /* Transform the child process to another program called Hello */
  18. /* Note the many variations of exec that exist! */
  19. printf("Parent: About to run hello program \n");
  20. if((value = execl("hello", "hello",0)) == -1) {
  21. perror("couldn’t do exec!!");
  22. exit(-1);
  23. }
  24. }
  25.  
  26. else { /* parent process */
  27. printf("Parent: my_process_id=%d,my_child’s_process_id=%d",getpid(), childpid);
  28. exit(0);
  29. } /* end if */
  30. }
Success #stdin #stdout #stderr 0.01s 5280KB
stdin
Standard input is empty
stdout
Parent: my_process_id=45847,my_child’s_process_id=45850child: my_process_id= 45850,parent_process_id=1
Parent: About to run hello program 
stderr
couldn’t do exec!!: No such file or directory