Process Api Code

 

Operating system process API  code:

Article catalog

  • Process API
    • Code1: RC = fork () the PID of the sub-process, when RC == 0, indicates the child process itself
    • Code2: The parent process uses wait () waiting to end the sub-process
    • Code3: EXEC () System Call - Make sub-process running with different processes of the parent process
    • Code4: Relocation output file
    • Process API

      Code1: RC = fork () the PID of the sub-process, when RC == 0, indicates the child process itself

      #include <stdio.h>
      #include <stdlib.h>
      #include <unistd.h>
      
      int
      main(int argc, char *argv[])
      {
          printf("hello world (pid:%d)\n", (int) getpid());
          int rc = fork();
          if (rc < 0) {
              
              fprintf(stderr, "fork failed\n");
              exit(1);
          } else if (rc == 0) {
                      printf("hello, I am child (pid:%d)\n", (int) getpid());
          } else {
             
              printf("hello, I am parent of %d (pid:%d)\n",
      	       rc, (int) getpid());
          }
          return 0;
      }
    • Code2: The parent process uses wait () waiting to end the sub-process

      1. What is WAIT () do? : Once the process calls Wait, immediately block yourself, automatically analyze if WAIT is automatically analyzed that the current process has exited, if it finds such a sub-process that has become zombie, Wait will collect this sub-process information, And returned it completely; if you didn't find such a child process, Wait would have been blocked here until there is an emergence.
      2. return value: If you perform success, the sub-process identification code (PID) is returned if there is an error occurs. Failure caused in Errno.
    • #include <stdio.h>
      #include <stdlib.h>
      #include <unistd.h>
      #include <sys/wait.h>
      
      int
      main(int argc, char *argv[])
      {
          printf("hello world (pid:%d)\n", (int) getpid());
          int rc = fork();
          if (rc < 0) {
              
              fprintf(stderr, "fork failed\n");
              exit(1);
          } else if (rc == 0) {
              
              printf("hello, I am child (pid:%d)\n", (int) getpid());
      	sleep(1);
          } else {
              
              int wc = wait(NULL);
              printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
      	       rc, wc, (int) getpid());
          }
          return 0;
      }