c - 为什么下面的语句打印三次?

标签 c multithreading fork

这是我的程序:

int main(int argc, char * argv[])
{
    pid_t child;
    int i=0;

    if( argc < 4 ){
        printf("Usage: %s <num_threads> <test_interval> <no_of_prints>\n", argv[0]);
        exit(1);
    }  

    // Some program logic goes here

    printf("context - switch \n\nPid\ttid\tNPid\tNtid\tJiffies\n\n");

    syscall(320);       

    child = fork();

    if(child == 0 ) { //in child
        fork();
        fork();
        process();
    }
    else    {
            wait(child);
            //Do some printing here 
    }

我的输出有 3 个(有时是 2 个)打印的“context - switch”printf 行。

最佳答案

这可能是因为 stdio 缓冲。简而言之,多个进程(父进程、它的子进程、孙进程等)以相同的缓冲区结束,并且它们在死亡时都将其写入屏幕。尝试:

printf("context - switch \n\nPid\ttid\tNPid\tNtid\tJiffies\n\n");
fflush(stdout);

或者可能只使用 write(2) 而不是 printf

关于c - 为什么下面的语句打印三次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554974/

相关文章:

c - 双核字数统计速度慢

c - 同步2个进程

c - 从接受两个字符串的 C 函数返回字符串

c - Golang C (.so) 在调用时导入分段违规

c - 具有 SIGFPE 异常的程序在 gdb 下表现不同

c# - 如何正确阻止方法直到对象计数器> 0?

c - fork 和 exec 与锁定共享内存相关 - C

perl - 如何通过管道使用 Parallel::ForkManager?

c - 为什么我的打印函数会用以下代码中的最后一个条目覆盖以前的条目?

multithreading - 并行编程==多线程编程?