编写两个不同的可执行程序,一个打开文件,一个读文件

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

makefile 文件

.SUFFIXES:.c .o

CC=gcc
SRCS1=homework.c
SRCS2=homework1.c

OBJS1=$(SRCS1:.c=.o)
OBJS2=$(SRCS2:.c=.o)

EXE1=homework
EXE2=homework1


all: $(OBJS1) $(OBJS2)
	$(CC) -o $(EXE1) $(OBJS1)
	$(CC) -o $(EXE2) $(OBJS2)
	@echo '----------------ok------------'

.c.o:
	$(CC) -Wall -g -o $@ -c $<

clean:
	-rm -f $(OBJS)
	-rm -f core*


打开文件的进程

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

int main(int arg, char *args[])
{
	int fd = open("a.txt", O_RDONLY);

	pid_t id = fork();

	if (id < 0)
	{
		return 0;
	}
	if (id > 0)
	{
		exit(0);
	}
	if (id == 0)
	{
		char s[10] = {0};
		sprintf(s, "%d", fd);
		char *argv[] = { "xsadsad", s, NULL };
		//char *envp[] = { "PATH=/bin", NULL };
		execve("homework1", argv, NULL);
	}



	return EXIT_SUCCESS;
}

读文件的进程

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

int main(int arg, char *args[])
{
	if (arg < 2)
	{
		return 1;
	}
	printf("%s\n", args[0]);
	printf("%s\n", args[1]);
	int fd = atoi(args[1]);

	char buf[100] = {0};

	read(fd, buf, 100);
	close(fd);
	printf("%s\n", buf);
	return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值