[英]printf prints same statement twice
下一個代碼應將PID編號寫入“ file.txt”,父進程為1,子進程為0。
我不確定代碼是否可以正常工作,但是我對Printf()遇到了一個奇怪的問題,那就是麻煩了。 我不明白為什么,但是printf兩次打印相同的語句。
碼:
#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;
}
而不是打印
My generation is 1.My pid is 8022
它打印
My generation is 1.My pid is 8
My generation is 1.My pid is 8
這是為什么?
謝謝!
該子項不會在print_pids()
退出,因此它將返回到main()
並打開文件,對其進行讀取,打印並退出。 父母也這樣做,但只有在孩子死后才這樣做。 如果您打印了執行打印操作的過程的PID,則可以更好地了解情況。
將write()
與固定大小的緩沖區一起使用也令人擔心。 而且沒有錯誤檢查。
這是代碼的固定版本-更相關的標頭,正確調用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;
}
樣本輸出:
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
請注意,獲取完整的消息長度如何幫助您了解正在發生的事情。 您的消息將截斷輸出,因此您看不到完整的PID。 並且兩個進程都將寫入文件(總共約72個字符)。 (可能會出現一些時序問題,以改變所看到的內容–我至少得到了一個異常結果,其中僅包含“我這一代”消息之一,但我無法可靠地重現該消息。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.