#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <unistd.h> char *EXIT_TYPE; int DELAY_BEFORE_EXIT; void * threadFunc(void *arg) { char *str = (char *) arg; for (int i = 0;; i++) { printf("%s is working .....\n", str); if (strcmp(str, "t1") == 0 && i >= DELAY_BEFORE_EXIT) { printf("t1 execing with: %s()\n", EXIT_TYPE); if (strcmp(EXIT_TYPE, "exit") == 0) exit(0); else if (strcmp(EXIT_TYPE, "_exit") == 0) _exit(0); else if (strcmp(EXIT_TYPE, "pthread_exit") == 0) pthread_exit(0); else if (strcmp(EXIT_TYPE, "return") == 0) return (0); } sleep(1); } } void usageError(char *progName) { fprintf(stderr, "usage: %s " "[_exit|exit|pthread_exit|return] " "[number-of-seconds-for-wait-before-exit]\n", progName); exit(EXIT_FAILURE); } void exitEN(int e, char *str) { if (str != NULL) fprintf(stderr, "%s: ", str); fprintf(stderr, "%s\n", strerror(e)); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { int s; pthread_t thr1, thr2; if (argc < 2) usageError(argv[0]); if (strcmp(argv[1], "_exit") != 0 && strcmp(argv[1], "exit") != 0 && strcmp(argv[1], "pthread_exit") != 0 && strcmp(argv[1], "return") != 0) usageError(argv[0]); EXIT_TYPE = argv[1]; if (argc > 2) DELAY_BEFORE_EXIT = atoi(argv[2]); else DELAY_BEFORE_EXIT = 3; s = pthread_create(&thr1, NULL, threadFunc, "t1"); if (s != 0) exitEN(s, NULL); s = pthread_create(&thr2, NULL, threadFunc, "t2"); if (s != 0) exitEN(s, NULL); pthread_exit(0); }
کلیه حقوق برای دارندهی سایت محفوظ است.