1. Write a program that calls fork(). Before calling fork(), have the main
process access a variable (e.g., x) and set its value to something (e.g., 100). What value is the variable in the child process? What happens to the variable when both the child and parent change the value of x?
#include<iostream> #include<unistd.h> #include<cstdlib> using namespace std; int main(){ int x=100; cout<<"main befor call:"<<x<<endl; size_t rc=fork(); if(rc=0){cout<<"child after call before change:"<<x<<endl; x++; cout<<"child after call after change:"<<x<<endl; } else{cout<<"parent after call before change:"<<x<<endl; x++; cout<<"parent after call after change:"<<x<<endl;} }
因为有不同的地址空间,所以x变量父子进程是不同的
2. Write a program that opens a file (with the open() system call) and then calls fork() to create a new process. Can both the child and parent access the file descriptor returned by open()? What happens when they are writing to the file concurrently, i.e., at the same time?
#include<iostream> #include<unistd.h> #include<cstdlib> #include<fcntl.h> #include<sys/wait.h> #include<string.h> #include<cassert> using namespace std; int main(){ close(STDOUT_FILENO); size_t fd=open("./mynums.txt",O_CREAT|O_WRONLY|O_TRUNC,S_IRWXU); size_t rc=fork(); if(rc=0){ cout<<"child after call after change:"<<endl; cout<<"child:"<<fd<<endl; cout<<endl; } else{cout<<"parent:"<<fd<<endl; cout<<"parent after call after change:"<<endl;} cout<<endl; }
就是介个,分别输出,当他们执行就像执行在命令行时候
3. Write another programusing fork(). The child process should print “hello”; the parent process should print “goodbye”. You should try to ensure that the child process always prints first; can you do this without calling wait() in the parent?
#include<iostream> #include<unistd.h> #include<cstdlib> #include<fcntl.h> #include<string> #include<cassert> using namespace std; int main(){ close(STDOUT_FILENO); size_t fd=open("./mytxt.txt",O_CREAT|O_WRONLY|O_TRUNC,S_IRWXU); size_t rc=fork(); if(rc==0){ cout<<"hello!"<<endl; cout<<endl; } else{ //sleep(3); cout<<"goodbye"<<endl; cout<<endl; } }
使用sleep,因为不需要阻塞就模拟等待wait
4. Write a program that calls fork() and then calls some form of exec() to run the program /bin/ls. See if you can try all of the variants of exec(), including (on Linux) execl(), execle(), execlp(), execv(), execvp(), and execvpe(). Why do you think there are so many variants of the same basic call?
#include<iostream> #include<unistd.h> #include<cstdlib> #include<fcntl.h> #include<string.h> #include<cassert> using namespace std; int main(){ size_t rc=fork(); if(rc<0){ assert("-1"); } else if(rc==0){ char *myargs[3]; myargs[0]=strdup("/bin/ls"); myargs[1]=strdup("ls"); myargs[2]=strdup("-al"); myargs[3]=NULL; execl("/bin/ls","ls","-al","..",NULL); cout<<endl; } else{ cout<<"goodbye"<<endl; cout<<endl; } }
这是通过execl的函数,execvp也使用过了,execle和execlp和execl差不多效果,其实execv也和execvp差不多,但是一个需要路径一个需要程序名