📄 tom.c
字号:
/* tom.c v4.0 */#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <pthread.h>static void tid2str(char * str, pthread_t tid){ sprintf(str, "%ld", tid);}void *thread0(void *arg){ char msg[] = "I love you.\n"; pthread_t tid = pthread_self(); char stid[256]; tid2str(stid, tid); if(fork()==0) { if (execlp("./jerry", "jerry", stid, msg, NULL)<0) { perror("execlp"); exit(EXIT_FAILURE); } } return NULL;}void *thread1(void *arg){ char msg[] = "I love you.\n"; pthread_t tid = pthread_self(); char stid[256]; tid2str(stid, tid); if(fork()==0) { if (execlp("./jerry", "jerry", stid, msg, NULL)<0) { perror("execlp"); exit(EXIT_FAILURE); } } return NULL;}void *thread2(void *arg){ char msg[] = "I love you.\n"; pthread_t tid = pthread_self(); char stid[256]; tid2str(stid, tid); if(fork()==0) { if (execlp("./jerry", "jerry", stid, msg, NULL)<0) { perror("execlp"); exit(EXIT_FAILURE); } } return NULL;}void *thread3(void *arg){ char msg[] = "I love you.\n"; pthread_t tid = pthread_self(); char stid[256]; tid2str(stid, tid); if(fork()==0) { if (execlp("./jerry", "jerry", stid, msg, NULL)<0) { perror("execlp"); exit(EXIT_FAILURE); } } return NULL;}void *thread4(void *arg){ char msg[] = "I love you.\n"; pthread_t tid = pthread_self(); char stid[256]; tid2str(stid, tid); if(fork()==0) { if (execlp("./jerry", "jerry", stid, msg, NULL)<0) { perror("execlp"); exit(EXIT_FAILURE); } } return NULL;}int main(){ int ret, i; pthread_t id[5]; ret = pthread_create(&id[0], NULL, thread0, NULL); if (ret!=0) { perror("pthread_creat"); exit(EXIT_FAILURE); } ret = pthread_create(&id[1], NULL, thread1, NULL); if (ret!=0) { perror("pthread_creat"); exit(EXIT_FAILURE); } ret = pthread_create(&id[2], NULL, thread2, NULL); if (ret!=0) { perror("pthread_creat"); exit(EXIT_FAILURE); } ret = pthread_create(&id[3], NULL, thread3, NULL); if (ret!=0) { perror("pthread_creat"); exit(EXIT_FAILURE); } ret = pthread_create(&id[4], NULL, thread4, NULL); if (ret!=0) { perror("pthread_creat"); exit(EXIT_FAILURE); } for (i=0; i<5; i++) { pthread_join(id[i], NULL); } exit(EXIT_SUCCESS);}/** * Can function "thread0" to "thread4" merge into only one function * "thread"? * * In this case we can't. Because we need different tid and stid to * use, if we merge them into one function, then all thread will use * same variable. */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -