Linux进程管理实验

一、编写程序pro1.c,在程序中创建一个子进程,使父子进程分别打印不同的内容,父进程换行打印“This is parent process”,子进程换行打印“This is child process”。

  1. 创建.c文件,命名为pro1.c,向里面添加以下代码:
    linux命令行文本编辑器真的很low,建议使用外部编辑器编辑,编辑好后然后上传保存到工作目录,然后命令行编译运行。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
	pid_t pid;
	pid = fork();							//调用fork()函数创建子进程
	if (pid == -1)							//创建失败
	{
		perror("fork error");
		exit(1);							//退出进程,指定返回值1
	}
	else if (pid > 0)						//父进程
	{
		printf("This is parent process\n");
	}
	else if (pid == 0)						//子进程
	{
		printf("This is child process\n");
	}
	printf("........finish..........\n");
	return 0;
}
  1. 将生成的C语言源文件编译成二进制可执行文件.o。
    $gcc -o pro1.o pro1.c

若运行失败,先安装gcc编辑器:$yum -y install gcc

  1. 运行pro1.o
    $./pro1.o
    在这里插入图片描述

二、编写程序pro2.c,在程序中创建一个子进程,使子进程通过exec更改代码段,执行cat命令。父进程换行打印“parent process:”及父进程id,子进程换行打印“child process:”及子进程id,另外子进程还要打印出“cat -b pro2.c”

  1. 创建pro2.c文件,添加以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
	pid_t pid;
	pid = fork();
	if (pid == -1)
	{
		perror("fork error");
		exit(1);
	}
	else if (pid > 0)
	{
		printf("parent process:pid=%d\n", getpid());
	}
	else if (pid == 0)
	{
		printf("child process:pid=%d\n", getpid());
		//execl("/bin/cat","-b","pro2.c",NULL);	//①
		//execlp("cat","-b","pro2.c",NULL);		//②
		char *arg[] = { "-b", "pro2.c", NULL };			//③
		execvp("cat", arg);
		perror("error exec\n");
		printf("child process:pid=%d\n", getpid());
	}
	return 0;
}

  1. 编译运行
    在这里插入图片描述
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值