简体   繁体   English

printf打印相同的语句两次

[英]printf prints same statement twice

the next code supposed to write to "file.txt" the PID number and 1 for Parent process or 0 for child process. 下一个代码应将PID编号写入“ file.txt”,父进程为1,子进程为0。

Im not sure if the code working as it should but im having a strange problem with Printf() that making trouble . 我不确定代码是否可以正常工作,但是我对Printf()遇到了一个奇怪的问题,那就是麻烦了。 i dont understand why, but printf prints the same statement twice. 我不明白为什么,但是printf两次打印相同的语句。

Code: 码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


void print_pids(int fd,int n){
int i,p;
char msg[99];

for(i=n;i>0;i--){
    p=fork();
    if(p>0){
        sprintf(msg,"My generation is 1.My pid is %d\n",getpid());
        write(fd,msg,33);
        wait();
    }
    if(p==0){
        sprintf(msg,"My generation is 0.My pid is %d\n",getpid());
        write(fd,msg,33);
    }
    if(p<0){
        printf("cannot fork");
        exit(0);
    }
}


}

void main(){
    int fd;
    char buf[99];
    fd=open("file.txt",O_WRONLY,700);
    print_pids(fd,1);
    close(fd);
    fd=open("file.txt",O_RDONLY,700);
    read(fd,buf,35);
    printf(" %s\n",buf);
    close(fd);
    return;


}

instead of printing 而不是打印

 My generation is 1.My pid is 8022

it prints 它打印

 My generation is 1.My pid is 8
 My generation is 1.My pid is 8

why is that? 这是为什么?

thanks! 谢谢!

The child doesn't exit in print_pids() , so it goes back to main() and opens the file, reads it, prints it, and then exits. 该子项不会在print_pids()退出,因此它将返回到main()并打开文件,对其进行读取,打印并退出。 The parent does the same, but only after the child has died. 父母也这样做,但只有在孩子死后才这样做。 If you printed the PID of the process doing the print operations, you'd be better informed. 如果您打印了执行打印操作的过程的PID,则可以更好地了解情况。

The use of write() with fixed size buffers is worrying, too. write()与固定大小的缓冲区一起使用也令人担心。 And there's no error checking. 而且没有错误检查。

Here's a fixed version of your code — more relevant headers, calling wait() correctly (you're unlucky your code didn't crash), printing the extra diagnostic information, writing the full length of the messages, reading and printing the full length of the messages (even though there isn't a null terminator), using an octal number ( 0600 ) rather than a decimal number ( 700 ) for the permissions, etc. 这是代码的固定版本-更相关的标头,正确调用wait() (不幸的是,您的代码没有崩溃),打印了额外的诊断信息,编写了消息的全长,阅读并打印了全长的消息(即使没有空终止符),也使用八进制数字( 0600 )而不是十进制数字( 700 )等。

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void print_pids(int fd, int n)
{
    int i, p;
    char msg[99];

    for (i = n; i > 0; i--)
    {
        p = fork();
        if (p > 0)
        {
            sprintf(msg, "My generation is 1. My pid is %d\n", getpid());
            write(fd, msg, strlen(msg));
            int status;
            int corpse = wait(&status);
            printf("Child %d exited with status 0x%.4X\n", corpse, status);
        }
        if (p == 0)
        {
            sprintf(msg, "My generation is 0. My pid is %d\n", getpid());
            write(fd, msg, strlen(msg));
        }
        if (p < 0)
        {
            printf("cannot fork");
            exit(0);
        }
    }
}

int main(void)
{
    int fd;
    char buf[99];
    fd = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0600);
    print_pids(fd, 1);
    close(fd);
    fd = open("file.txt", O_RDONLY);
    int nbytes = read(fd, buf, sizeof(buf));
    printf("%.5d: %.*s\n", (int)getpid(), nbytes, buf);
    close(fd);
    return 0;
}

Sample output: 样本输出:

33115: My generation is 1. My pid is 33112
My generation is 0. My pid is 33115

Child 33115 exited with status 0x0000
33112: My generation is 1. My pid is 33112
My generation is 0. My pid is 33115

Notice how getting the full length of message helps you see what's going on. 请注意,获取完整的消息长度如何帮助您了解正在发生的事情。 Your messages were truncating the output, so you didn't see the full PIDs. 您的消息将截断输出,因此您看不到完整的PID。 And both processes write into the file (about 72 characters in total). 并且两个进程都将写入文件(总共约72个字符)。 (There could be some timing issues to alter what is seen — I got at least one anomalous result with only one of the 'My generation' messages in it, but I couldn't reproduce that reliably.) (可能会出现一些时序问题,以改变所看到的内容–我至少得到了一个异常结果,其中仅包含“我这一代”消息之一,但我无法可靠地重现该消息。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM