fork()

linux中fork()函数详解中的第一个程序,修改了下,具体如下:

#include <unistd.h>
#include <stdio.h>
int main ()
{
    pid_t fpid; //fpid表示fork函数返回的值
    int count=0;

	printf("========================\n");
    fpid=fork();
	printf("------------------------\n");
    if (fpid == 0) {
        printf("i am the child process, my process id is %d\n",getpid());
        printf("我是儿子\n");//对某些人来说中文看着更直白。
        count++;
        printf("fpid = %d\n", fpid);
    } else if (fpid > 0 ){
        sleep(3);
        printf("i am the parent process, my process id is %d\n",getpid());
        printf("我是他爹\n");
        count++;
        printf("fpid = %d\n", fpid);
    } else {
        printf("error in fork!");
    }

    printf("\n -------------\n统计结果是: %d\n",count);
    return 0;
}

运行结果如下:

========================
------------------------
------------------------
i am the child process, my process id is 13
我是儿子
fpid = 0
-------------
统计结果是: 1
i am the parent process, my process id is 12
我是他爹
fpid = 13
-------------
统计结果是: 1

猜你喜欢

转载自blog.csdn.net/sy_123a/article/details/108099888