操作系统---之子父进程的创建

本文通过三个示例详细解析了如何使用C语言进行进程创建及管道通信:首先展示了如何通过fork()创建子进程并控制输出顺序;其次,通过另一个fork()示例进一步探讨了进程间的输出顺序不确定性;最后,通过pipe()实现子进程向父进程发送消息的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C/C++ code ?
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值