第一次接触多线程。
自学党,最近买了本在吭,好难的说。
看了书上有关多线程的部分,然后本人本人写了个 代码
本人希望是这样的,主函数里fork()一个进程,创建之后3秒父进程输出一个字符串,创建后子进程每个两秒输出一个字符串
#include
#include
#include
#include
int main(void)
{
pid_t pid;
if((pid = fork())
{
printf("Fork失败.\n");
exit(1);
}
else if(pid == 0) //子进程输出
{
for(int i = 0 ; i
{
sleep(2);
printf("%dth.\n",i+1);
}
}
else //父进程输出
{
sleep(3);
printf("This Is Fork.");
}
return 0;
}
本人当时的期望是这样的
1th.
This Is Fork.
3th.
4th.
5th.
6th.
7th.
8th.
9th.
10th.
jrf@jrf-desktop:~/unix$ 2th.
但实际输出是这样的
1th.
This Is Fork.jxf@jxf-desktop:~/unix$ 2th.
3th.
4th.
5th.
6th.
7th.
8th.
9th.
10th.
^C
注意最后本人还是用ctrl+c来结束的。
然后本人觉得是子进程执行的时间(20S)比父进程所需要的时间(3S)长,所以父进程执行完了再执行return 0语句结束,然后那个子进程还继续执行玩了并且没有结束。
然后本人看了树上wait()函数的作用,所以本人想附近从输出字符后用wait()阻塞,等子进程执行完了再执行return 0语句,于是本人在代码上加了个wait()函数。
#include
#include
#include
#include
#include
int main(void)
{
pid_t pid;
if((pid = fork())
{
printf("Fork失败.\n");
exit(1);
}
else if(pid == 0)
{
for(int i = 0 ; i
{
sleep(2);
printf("%dth.\n",i+1);
}
}
else
{
sleep(3);
printf("This Is Fork.");
waitpid(pid,NULL,2); //唯一的变化就是加了个wait()函数
}
return 0;
}
然后输出是这样的
1th.
2th.
3th.
4th.
5th.
6th.
7th.
8th.
9th.
10th.
This Is Fork.jrf@jrf-desktop:~/unix$
本人现在知道其实这个wait()加了也无法达成最初的目标,但本人奇怪的是本人的wait()函数加在printf()函数后面的,C语言假如是逐行执行的话,不是应该执行完printf()函数在阻塞父进程的么?