下一个代码应将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个字符)。(可能会出现一些时序问题,以改变所看到的内容–我至少得到了一个异常结果,其中仅包含“我这一代”消息之一,但我无法可靠地重现该消息。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句