0
点赞
收藏
分享

微信扫一扫

linux下的C语言开发(进程等待)

    所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
pid_t pid;

pid = fork();
if(0 == pid)
{
printf("This is child process, %d\n", getpid());
sleep(5);
}
else
{
wait(NULL);
printf("This is parent process, %d\n", getpid());
}

return 1;
}

    下面,我们需要做的就是两步,首先输入gcc fork.c -o fork, 然后输入./fork,就会在console下面获得这样的结果。

[root@localhost fork]# ./fork
This is child process, 2135
This is parent process, 2134


举报

相关推荐

0 条评论