我正在運行一個程序,它在控制檯上打印所有的printf語句。 但是當我嘗試使用'>'將它們重定向到任何文件時,文件被創建,但文件中沒有輸出程序。 請幫助 當我運行在控制檯下面的代碼:重定向運算符不在unix中工作?
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
double time_diff(struct timeval x , struct timeval y);
struct timeval initial;
long sno=0;
void *process1 (void *sleepTimeForP1);
void *process2 (void *sleepTimeForP2);
pthread_mutex_t lock;
int main()
{
gettimeofday(&initial , NULL);
pthread_t trd1,trd2;
int thread1,thread2;
int var1;
int var2;
int *sleepTimeForP1;
int *sleepTimeForP2;
var1=rand()%9+1;
sleepTimeForP1=&var1;
var2=rand()%9+1;
sleepTimeForP2=&var2;
printf("S No.\tThread Number\tItem\tTime(usec)\n");
thread1=pthread_create(&trd1,NULL,process1,(void *)sleepTimeForP1);
thread2=pthread_create(&trd2,NULL,process2,(void *)sleepTimeForP2);
pthread_join(trd1, NULL);
pthread_join(trd2, NULL);
printf("pthread1 = %d\n",thread1);
printf("pthread2 = %d\n",thread2);
return 0;
}
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
void *process1 (void *sleepTimeForP1)
{
int *tsleepTimeForP1 = (int *)sleepTimeForP1;
struct timeval end;
while(1)
{
pthread_mutex_lock(&lock);
sno++;
gettimeofday(&end , NULL);
printf("%ld\t1\t\t1.1\t%.0lf\n",sno,time_diff(initial, end));
sno++;
gettimeofday(&end , NULL);
printf("%ld\t1\t\t1.2\t%.0lf\n",sno,time_diff(initial, end));
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *process2 (void *sleepTimeForP2)
{
int *tsleepTimeForP2 = (int *)sleepTimeForP2;
struct timeval end;
while(1)
{
pthread_mutex_lock(&lock);
sno++;
gettimeofday(&end , NULL);
printf("%ld\t2\t\t2.1\t%.0lf\n",sno,time_diff(initial, end));
sno++;
gettimeofday(&end , NULL);
printf("%ld\t2\t\t2.2\t%.0lf\n",sno,time_diff(initial, end));
pthread_mutex_unlock(&lock);
sleep(1);
}
}
它給我下面的輸出:
S No. Thread Number Item Time(usec)
1 1 1.1 320
2 1 1.2 438
3 2 2.1 506
4 2 2.2 586
5 1 1.1 1000592
6 1 1.2 1000629
7 2 2.1 1000714
8 2 2.2 1000740
9 1 1.1 2000820
10 1 1.2 2000927
11 2 2.1 2000998
12 2 2.2 2001099
13 1 1.1 3001165
14 1 1.2 3001285
15 2 2.1 3001355
16 2 2.2 3001441
17 1 1.1 4001518
18 1 1.2 4001635
19 2 2.1 4001706
20 2 2.2 4001798
21 1 1.1 5001776
但是當我做./a.out> b.txt 我不在控制檯上以及在文件中沒有任何輸出
發佈[最小完整可驗證示例](http://stackoverflow.com/help/mcve)會使這個問題更容易回答。 – user3386109
告訴我們你想要做什麼?你打印到標準輸出? –
緩衝。您是否在等待程序在查看文件之前完成,或者您是否在嘗試查看它仍在運行但尚未實際寫入任何數據? –