
作业社区
探索学习新天地,共享知识资源!
慕运维8597106 的学生作业:
#include #include #include #include #include #include int main() { pid_t cpid = fork(); if (cpid == -1) { perror("[ERROR fork]"); exit(EXIT_FAILURE); } else if (cpid == 0) { printf("child process A running:%ld\n", time(NULL)); sleep(2); exit(EXIT_SUCCESS); } else if (cpid > 0) { pid_t cpid2 = fork(); if (cpid2 == -1) { perror("[ERROR fork]"); exit(EXIT_FAILURE); } else if (cpid2 == 0) { printf("child process B running:%ld\n", time(NULL)); sleep(5); exit(EXIT_SUCCESS); } else if (cpid2 > 0) { int status1, status2 = 0; while ((waitpid(cpid, &status1, WNOHANG)) == 0 || (waitpid(cpid2, &status2, WNOHANG) == 0)) { } } } printf("All child processes have finished:%ld\n", time(NULL)); return 0; } 【图片】





慕运维8597106 的学生作业:
#include #include #include int main() { int global = 0; const pid_t pid = fork(); if(pid == -1){ perror("[Error] fork()"); return -1; } if(pid == 0){ global = 100; printf("我在子进程中,global=%d\n",global); } if(pid > 0){ printf("我在主进程中,子进程pid=%d,global=%d\n",pid,global); } return 0; } 【图片】 原因:子进程会拷贝父进程的地址空间,在子进程中修改的只是自己的global,不会影响到付进程的global





向佐佐 的学生作业:
#include #include #include #include #include #include static int number=0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_handler(void *arg) { int cnt = atoi((char *)arg); int i; for(i=0;i0) { total_consume++; printf("消费一个产品,产品数量:%d\n",--number); done = total_consume >= total_product; } pthread_mutex_unlock(&mutex); if(done) { break; } } return 0; } 【图片】




