1 在linux系统中运行12-7中的程序,但把结果重定向到文件中,解释结果。
下面是12-7的代码:
#include <stdio.h> #include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare() { printf("preparing locks\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent() { printf("parent unlocking locks\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child() { printf("child unlocking locks\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started\n"); pause(); return 0; } int main(int argc, char const *argv[]) { int err; pid_t pid; pthread_t tid; if((err = pthread_atfork(prepare, parent, child)) != 0) { printf("can‘t install fork handlers\n"); } if((err = pthread_create(&tid, NULL, thr_fn, 0)) != 0) { printf("can‘t create thread\n"); } sleep(2); printf("parent about to fork\n"); if((pid = fork()) < 0) { printf("fork failed\n"); } else if(pid == 0) { printf("child returned from fork\n"); } else { printf("parent returned from fork\n"); } return 0; }
thread started parent about to fork preparing locks parent unlocking locks parent returned from fork thread started parent about to fork preparing locks child unlocking locks child returned from fork
thread started parent about to fork
thread started parent about to fork preparing locks
thread started parent about to fork preparing locks
//父进程的缓冲区中的内容 thread started parent about to fork preparing locks parent unlocking locks parent returned from fork //子进程的缓冲区中的内容 thread started parent about to fork preparing locks child unlocking locks child returned from fork
等两个进程结束后就会输出到文件了,结果如开始所示。
从这个结果也可以看出,fork()产生一个进程后,确实返回两次,先返回到父进程,再返回到子进程。
其它题目现在看不太懂,待补充。。。
[APUE] 第12张习题解答,布布扣,bubuko.com
原文:http://blog.csdn.net/luofengmacheng/article/details/24020293