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;
}
本文介绍了一个父进程通过调用open函数打开文件,并通过fork创建子进程的方式,让子进程仅使用read函数来读取同一文件的具体实现。该实现遵循特定的限制条件,即子进程不允许直接使用open或fopen函数。
1万+

被折叠的 条评论
为什么被折叠?



