1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
main()
{
if
( fork() == 0 )
// 子进程1
{
printf
(
"b\n"
);
exit
(0);
}
else
{
if
( fork() == 0 )
// 子进程2
{
printf
(
"c\n"
);
exit
(0);
}
printf
(
"a\n"
);
// 父进程
exit
(0);
}
}
|
多次执行的话,a/b/c的显示顺序不一定,取决于进程的调度时机
二:
编写一段程序,使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符;父进程显示字符“a”,子进程分别显示字符“b”和“c”。试观察记录屏幕上的显示结果,并分析原因。 〈程序〉 #include<stdio.h> main() { int p1,p2; if(p1=fork()) /*子进程创建成功*/ putchar('b'); else { if(p2=fork()) /*子进程创建成功*/ putchar('c'); else putchar('a'); /*父进程执行*/ } } <运行结果> bca(有时会出现abc的任意的排列) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向通道个写一句话: child1 process is sending message! child2 process is sending message! 而父进程则从管道中读出来自两个进程的信息,显示在屏幕上。 〈程序〉 #include <unistd.h> #include <signal.h> #include <stdio.h> int pid1,pid2; main( ) { int fd[2]; char outpipe[100],inpipe[100]; pipe(fd); /*创建一个管道*/ while ((pid1=fork( ))==-1); if(pid1==0) { lockf(fd[1],1,0); sprintf(outpipe,"child 1 process is sending message!"); /*把串放入数组outpipe中*/ write(fd[1],outpipe,50); /*向管道写长为50字节的串*/ sleep(5); /*自我阻塞5秒*/ lockf(fd[1],0,0); exit(0); } else { while((pid2=fork( ))==-1); if(pid2==0) { lockf(fd[1],1,0); /*互斥*/ sprintf(outpipe,"child 2 process is sending message!"); write(fd[1],outpipe,50); sleep(5); lockf(fd[1],0,0); exit(0); } else { wait(0); /*同步*/ read(fd[0],inpipe,50); /*从管道中读长为50字节的串*/ printf("%s\n",inpipe); wait(0); read(fd[0],inpipe,50); printf("%s\n",inpipe); exit(0); } } } 〈运行结果〉 延迟5秒后显示: child1 process is sending message! 再延迟5秒: child2 process is sending message!转载:https://zhidao.baidu.com/question/357812494.html
转载:https://bbs.youkuaiyun.com/topics/350124755