抱歉,这可能是一个愚蠢或微不足道的问题。我有一个像这样编写的代码,用于将一些内容写入文本文件。
我调用 fork() 并创建了一个孩子。
我的问题是在我的 write() 调用中,我没有在 write() 调用中包含任何字符串“main”,但不知何故,当我查看输出时,有两行包含字符串“main”,例如这个:
以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int fd = open("SomeFile.txt", O_WRONLY | O_CREAT | O_APPEND);
assert(fd > -1);
// fork a child process
int fChild = fork();
if(fChild < 0) {
fprintf(stderr, "fork is failing !\n");
//exit(1);
} else {
sleep(7);
int childNumb = write(fd, "A Message from Child!\n", 35);
}
int sec = write(fd, "Message From parent!\n", 29);
close(fd);
}
我不确定为什么字符串“main”被写入文本文件。有人可以告诉我发生了什么事吗?
谢谢你
请尝试一次。我不确定它是否有效,但是当您尝试时请回复我。
如果写入函数在写入预期字节数之前遇到空终止符 ( ),它可能会从内存中写入其他数据,如果存储在附近,则可能包括字符串“main”。
在写入之前使用
strlen
确定字符串的准确长度:
int childNumb = write(fd, "A Message from Child!\n", strlen("A Message from Child!\n"));
int sec = write(fd, "Message From parent!\n", strlen("Message From parent!\n"));