Linux实验五:Linux环境下的C语言编程


一、实验目的:

1、学会用系统调用和库函数进行编程

2、加深对进程概念的理解,明确进程和程序的区别。

3、进一步认识并发执行的实质。

4、分析进程竞争资源现象,学习解决进程互斥的方法。

5、了解Linux系统中进程通信的基本原理。


二、实验要求

1、用fork( )创建进程,观察进程的并发执行

2、使用管道、消息队列机制进行进程间通信


三、实验内容

1、编写一段C语言程序使其完成:父进程创建两个子进程,每个进程都在屏幕上显示自己的进程ID号。

运行结果示例:

# ./forktest
this is child1:16602
this is child2:16603
this is parent:16601

在这里插入图片描述

在这里插入图片描述


2、上机调试下面的程序,观察运行结果,分析原因。

#include <sys/types.h>
#include <unistd.h>
int glob=3;
int main()
{
    
    
        pid_t pid;
        int loc=3;
        printf("befor fork():glob=%d,loc=%d\n", glob, loc);
        if ((pid=fork()) < 0)
        {
    
    
                printf("fork() error\n");
                exit(0);
        }
        else if (pid == 0)
        {
    
    
                glob++;
                loc--;
                printf("child:glob=%d, loc=%d\n", glob, loc);
        else
        {
    
    
                printf("parent:glob=%d, loc=%d\n", glob, loc);
                exit(0);
        }
        return 0;
}

在这里插入图片描述
在这里插入图片描述

fork()后会有两个并发进程执行,子进程赋值了父进程的数据段,包括全局变量。父进程执行进入pid>0的情况,子进程进入pid==0的情况,分别做glob和loc的运算以及输出。


3、利用两个管道进行双向通信,实现父子进程协作把整数x从1加到10。

运行结果示例:

# ./pipetest
child 5938 read: 1                 
parent 5937 read: 2
child 5938 read: 3
parent 5937 read: 4
child 5938 read: 5
parent 5937 read: 6
child 5938 read: 7
parent 5937 read: 8
child 5938 read: 9
parent 5937 read: 10
·说明:5938和5937分别是子进程和父进程的pid

在这里插入图片描述

在这里插入图片描述


4、利用消息队列实现父子进程的通信。父进程创建消息队列,并向消息队列发送消息;子进程接受消息;父进程等待子进程接收消息后删除消息队列。

运行结果示例:

# ./msgtest
Parent:Send to the message queue successfully!
The message sent is :This is the input! 
Child:Receiving from the message queue:This is the input!

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Jormungand_V/article/details/109391591
今日推荐