1. 创建子进程,满足下列要求。
a) 先让子进程输出当前所在位置
b) 再让父进程在当前目录下新建一个名为hise的文件夹
c) 输出子进程和父进程的pid号
d) 最后让父进程将程序源码文件(.c)拷贝到新建的hise文件夹
2. 在Linux下练习使用fork()创建进程(可参考课本P92页或者PPTChap 3),增加全局变量,在子进程与父进程中分别对全局变量进行修改,并打印出结果。可针对下列两种情况分别设计,给出结果并分析原因。
a) 如果父进程要等待子进程结束再进行;
b) 如果父进程不等待子进程。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
int main(int argc, char * argv[]) {
int fd[2];
pid_t pid;
if(pipe(fd) < 0) {
perror("pipe");
exit(1);
}
if((pid = fork()) < 0) {
perror("fork");
exit(2);
}else if(pid == 0) {
close(fd[0]);
char path1[1024] = {0};
getcwd(path1, sizeof(path1));
printf("child path1 ==== %s\n", path1);
write(fd[1], path1, strlen(path1));
printf("child PID = %d, parent PID = %d\n", getpid(), getppid());
sleep(3);
} else {
char path2[1024] = {0};
char buf[1024];
close(fd[1]);
int flg = fcntl(fd[0], F_GETFL);
flg |= O_NONBLOCK;
fcntl(fd[0], F_SETFL);
read(fd[0], buf, sizeof(buf));
printf("parent buf = %s\n", buf);
umask(0000);
if(mkdir("hise", 0755)) {
perror("mkdir");
exit(1);
}
chdir("hise");
int fd_file = open("./01.c",O_RDONLY);
int fd_file2 = open("./cp01.c",O_WRONLY | O_CREAT, 0644);
int buf2[1024];
memset(buf2, 0, 1024);
while(read(fd_file, buf2, sizeof(buf2)-1) > 0 ) {
write(fd_file2, buf2, strlen(buf2));
}
wait(NULL);
sleep(3);
}
return 0;
}
追问哇这么麻烦的吗,,,我们是第三次上这个操作系统课,,老师什么都没讲就要这么长吗,,,而且第二问好像没有写啊
追答第二个问题我也不知道书本啊; 没有办法参考; 不要说教材都差不多, 我只是一个初中生; 压根没有看过国内的教材; 做出来就可能错太多了; 当然如果说全局变量验证用于子进程和父进程一起使用,那么可以告诉你这个是很难控制全局变量的结果的, 包括线程中也一样;当然linux只是用户线程而非内核线程, 但是对于全局变量都一样; 而如果要修改线程和进程间基础通信通常用函数, 而这些函数通常都是传出参数; 如果库中有的基本都是那些get...的和_r结尾的函数; 这些函数基本都有一个指针用于传出函数;
这么点代码也叫麻烦啊! 你要求就4个点了., 而每个点也就平均3行代码, 其他是要使用的库的头文件和标准格式而已;