the address of pdf
http://pages.cs.wisc.edu/~remzi/OSTEP/cpu-api.pdf
homework 1
#include
#include
#include
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int x = 100;
int rc = fork();
if (rc < 0 ){
printf("fork process failed\n");
exit(1);
} else if (rc == 0) {
x++;
printf("x=%d\n",x);
printf("hello, I am child (pid:%d)\n", (int) getpid());
} else {
x++;
printf("x=%d\n",x);
printf("hello, I am parent of %d (pid:%d)\n", rc, (int) getpid());
}
printf("finaly x=%d\n",x);
return 0;
}
parent and child process both add x from 100; 是不是并发时变量的更改时不受控制的,在并发中应该解决这个问题。
homework 2
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0 ){
printf("fork process failed\n");
exit(1);
} else if (rc == 0) {
close(STDOUT_FILENO);
open("./h2.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
printf("hello, I am child (pid:%d)\n", (int) getpid());
} else {
close(STDOUT_FILENO);
open("./h2.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
printf("hello, I am parent of %d (pid:%d)\n", rc, (int) getpid());
}
return 0;
}
the content of file h2.output
hello, I am child (pid:21820)
是否是只有子进程才能操作文件???
homework 3
#include
#include
#include
#include
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0 ){
printf("fork process failed\n");
exit(1);
} else if (rc == 0) {
printf("hello, I am child (pid:%d)\n", (int) getpid());
} else {
do {
sleep(1);
} while (waitpid(-1,NULL,WNOHANG) == 0);
printf("goodbye, I am parent of %d (pid:%d)\n", rc, (int) getpid());
}
return 0;
}
homework4
#include
#include
#include
#include
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0 ){
printf("fork process failed\n");
exit(1);
} else if (rc == 0) {
printf("hello, I am child (pid:%d)\n", (int) getpid());
char *myargs[3];
myargs[0] = strdup("ls");
myargs[1] = strdup("./");
myargs[2] = NULL;
execl("/bin/ls", "ls", "-al", "./", (char *) 0);
//first
//execvp(myargs[0], myargs);
printf("this shouldn't print out\n");
} else {
//父进程会运行的,如果使用了wait会等待子进程完成之后再运行
int wc = wait (NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n", rc, wc, (int) getpid());
}
return 0;
}
homework 5
#include
#include
#include
#include
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0 ){
printf("fork process failed\n");
exit(1);
} else if (rc == 0) {
int test = wait(NULL);
printf("hello, I am child (pid:%d) (wid:%d)\n", (int) getpid(), test);
char *myargs[3];
myargs[0] = strdup("wc");
myargs[1] = strdup("p3.c");
myargs[2] = NULL;
execvp(myargs[0], myargs);
printf("this shouldn't print out");
} else {
//父进程会运行的,如果使用了wait会等待子进程完成之后再运行
int wc = wait (NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n", rc, wc, (int) getpid());
}
return 0;
}