2.练习,fork和execve的使用。

a.txt文件内容如下:
hello world


  编写两个不同的可执行程序,名称分别为a和b,b为a的子进程。在a程序中调用open函数打开a.txt文件。在b程序不可以调用open或者fopen,只允许调用read函数来实现读取a.txt文件。(a程序中可以使用 fork与execve函数创建子进程)。


在调用fork是文件描述符和一些全局变量是共享的,及时是调用了execve这些变量仍让有效。


main.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


int main(void)
{
	pid_t pid = 0;
	pid = fork();
	
	int fd = open("a.txt", O_RDONLY);




	if(pid == 0)
	{
	/*	char buf[128] = { 0 };
		read(fd, buf, sizeof(buf));
		printf("%s\n", buf);
	*/
		char temp[8] = {0};
		sprintf(temp, "%d", fd);
		char *args[] = {"main2",temp, NULL}; 
		execve("main2", args, NULL);
	}
	else if(pid > 0)
	{
			
		char buf[128] = { 0 };
		read(fd, buf, sizeof(buf));
		printf("parent %s\n", buf);
	}


    return EXIT_SUCCESS;
}


main2.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


int main(int arg, char *argc[])
{
		int fd = atoi(argc[1]);
		char buf[128] = { 0 };
		read(fd, buf, sizeof(buf));
		printf("%s\n", buf);
    return EXIT_SUCCESS;
}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值