process processing

 

1. creat process --->  fork()

 

#include <sys/types.h>

#include <unistd.h>

pid_t fork(void)

 

fork() creates a child process,  it is arbitrary for once calling and twice return.

in parent process:

      return pid of child process

in child process:

      return 0

2. communication between parent and child ---> wait() & waitpid()

 

#include <sys/types.h>

#include <sys/wait.h>

pid_t wait(int *status);

pid_t waitpid(pid_t pid, int *status, int options);

 

3. exec() family --->execv()

#include <unistd.h>

 

extern char **environ;

 

int execl(const char *path, const char *arg, ...);

int execlp(const char *file, const char *arg, ...);

int execle(const char *path, const char *arg, ...,

                    char * const envp[] );

int execv(const char *path, char *const argv[]);

int execvp(const char *file, char *const argv[]);

Note: l -> list,  v -> vector (must end with (char*)0 )

 

these three ones always combine together, such as followings:

refer to :服务器进程的两次fork()

http://www.linuxidc.com/linux/2011-08/40590.htm

 

0.int

1.main(void) 
 2.{ 
 3.    pid_t        pid; 
 4. 
 5.    if ( (pid = fork()) < 0) 
 6.          err_sys("fork error"); 
 7.    else if (pid == 0)  
 8.        {                /* first child */ 
 9.           if ( (pid = fork()) < 0) 
 10.                        err_sys("fork error"); 
 11.           else if (pid > 0) 
 12.                 exit(0);        /* parent from second fork == first child */ 
 13. 
 14.                /* We're the second child; our parent becomes init as soon
 15.                   as our real parent calls exit() in the statement above.
 16.                   Here's where we'd continue executing, knowing that when
 17.                   we're done, init will reap our status. */ 
 18. 
 19.            sleep(2); 
 20.            printf("second child, parent pid = %d\n", getppid()); 
 21.            exit(0); 
 22.        } 
 23. 
 24.    if (waitpid(pid, NULL, 0) != pid)        /* wait for first child */ 
 25.            err_sys("waitpid error"); 
 26. 
 27.        /* We're the parent (the original process); we continue executing,
 28.           knowing that we're not the parent of the second child. */ 
 29. 
 30.    exit(0); 
 31.}