C语言多线程输出不正常求高手指点

来源:百度知道 编辑:UC知道 时间:2024/05/25 10:01:50
在linux下写的一个小练习,通过用pthread 和 popen管道
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>

void *fun_ping(void *att);
sem_t sem;
char str[BUFSIZ];

int main(int argc, char **argv) {
int i = 1;
int res;
pthread_t thread;
sem_init(&sem, 0, 3);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for (; i <= 255; i++) {
sem_wait(&sem);
sprintf(str, "ping -c 1 117.88.34.%d", i);
res = pthread_create(&thread, &attr, fun_ping, str);
if (res != 0) {
fprintf(stderr, "create thread failed\n");
}
}
sem_wait(&sem);
sem_wait(&sem);
sem_wait(&sem);
sem_destroy(&sem);
exit(EXIT_SUCCESS);
}

void *fun_ping(v

线程参数,传地址使用动态分配吧,你只用一个buffer,后面的很可能就把前面的给覆盖了。

把所有的输出printf使用一个互斥的信号量同步一下就行了吧,C的标准库不是线程安全的。