您的位置:首页 > 其它

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

2016-07-09 12:54 597 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: