2009年1月23日 星期五

Linux fork

fork() 基礎
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(){
    pid_t pid;
    int rv;
    switch(pid=fork()) {
        case -1:
            perror("fork"); /* something went wrong */
            exit(1); /* parent exits */
        case 0:
            printf(" CHILD: This is the child process!\n");
            printf(" CHILD: My PID is %d\n", getpid());
            printf(" CHILD: My parent's PID is %d\n", getppid());
            printf(" CHILD: Enter my exit status (make it small): ");
            scanf(" %d", &rv);
            printf(" CHILD: I'm outta here!\n");
            exit(rv);
        default:
            printf("PARENT: This is the parent process!\n");
            printf("PARENT: My PID is %d\n", getpid());
            printf("PARENT: My child's PID is %d\n", pid);
            printf("PARENT: I'm now waiting for my child to exit()...\n");
            wait(&rv); /* wait until child leave */
            printf("PARENT: My child's exit status is: %d\n", WEXITSTATUS(rv));
            printf("PARENT: I'm outta here!\n");
    }
    return 0;
}


Linux / Unix Command: execvp
The exec family of functions replaces the current process image with a new process image. So if you want to execute a command in a application, better use fork() to create a child thread.

execute a file execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe()

linux c 進程操作篇

1 則留言:

Unknown 提到...

淺議Unix的defunct進程(“僵屍”進程)
http://fanqiang.chinaunix.net/a1/b5/20020417/080200185_b.html

fork和defunct(殭屍)進程
http://blog.csdn.net/axes/archive/2006/06/07/777743.aspx

Powered By Blogger