'Why is write duplicating text in parent process?
I am reading Operating Systems Three Easy Pieces. While working through one of the exercises, I encountered an interesting behavior related to the 'write' system call. The program is as follows,
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
int fd = open("./some_file.txt", O_CREAT | O_WRONLY | O_APPEND, 0777);
int rc = fork();
if (rc < 0)
{
printf("Fork failed\n");
exit(10);
}
else if (rc == 0)
{
write(fd, "the sun shines so bright\n", 26);
}
else
{
wait(NULL);
int e = write(fd, "it's a cold night outside \n", 36);
if (e == -1)
{
printf("error writing to fd, %s", strerror(errno));
exit(-1);
}
}
return 0;
}
As the parent process waits for the child process to finish, the output of this program is,
the sun shines so bright
it's a cold night outside
which is expected. However, if I change the # of bytes to write in child process from 26 to 36,
write(fd, "the sun shines so bright\n", 36);
the output changes to
the sun shines so bright
it's a colit's a cold night outside
_________^ 10 bytes
The child process string (the sun shines so bright\n\0) is 26 bytes. The additional 10 bytes are causing this behavior. I have tried different values for the write statement in child process and the behavior is consistent. Can someone please explain why this is happening?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
