阅读量:0
1、wait 函数
宏定义:WIFEXITED() WEXITSTATUS()
调用进程 一般不做额外的事情
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> int main(int argc, const char *argv[]) { pid_t pid = fork(); if (-1 == pid) { perror("fork fail"); return -1; } if (pid > 0) { int status; printf("father ----\n"); wait(&status); printf("status = %d\n",status); if (WIFEXITED(status)) { printf("status = %d\n",WEXITSTATUS(status)); } }else if (pid == 0) { printf("child exit \n"); exit(256); } return 0; }
2、waitpid 函数
调用进程 逻辑一般不受影响
注意:waitpid 想要处理到子进程必须套在循环中
3、pthread_库函数
(1)创建线程
(2)获取线程的tid
(3)pthread_join函数:等待线程结束
创建结束线程
#include <stdio.h> #include <pthread.h> #include <errno.h> #include <unistd.h> void * do_something(void *arg) { static int a = 10; //线程的任务函数 printf("------do_something ---- \n"); //pthread_exit(NULL); pthread_exit(&a); //pthread_exit((void *)a); } int main(int argc, const char *argv[]) { pthread_t tid; int ret = pthread_create(&tid,NULL,do_something,NULL); if (ret != 0) { errno = ret; perror("pthread_create fail"); return -1; } //sleep(3); void *retval; //pthread_join(tid,&retval); pthread_join(tid,&retval); printf("---- main----%d\n",*(int *)retval); // printf("---- main----%d\n",(int)retval); pthread_exit(NULL); return 0; }
#include <stdio.h> #include <pthread.h> #include <errno.h> #include <unistd.h> void * do_something1(void *arg) { int *p = arg; //((int)(*arg))+=1; int a = *p; while (1) { //线程的任务函数 printf("------do_something1 ---- tid = %ld a = %d\n",pthread_self(),a++); sleep(1); } } void * do_something2(void *arg) { int *p = arg; //线程的任务函数 int a = *p; while (1) { a += 2; printf("------do_something2 ---- tid = %ld a = %d\n",pthread_self(),a); sleep(1); } } int main(int argc, const char *argv[]) { int a = 10; pthread_t tid1; int ret = pthread_create(&tid1,NULL,do_something1,&a); if (ret != 0) { errno = ret; perror("pthread_create fail"); return -1; } pthread_t tid2; ret = pthread_create(&tid2,NULL,do_something2,&a ); if (ret != 0) { errno = ret; perror("pthread_create fail"); return -1; } //main do something while (1) { printf("----main-----do_something--tid = %ld-\n",pthread_self()); sleep(1); } sleep(3); return 0; }