Trouble sharing files between processes.
I'm having trouble sharing files between processes. Here's what I have:
parent.c
Code:
#include <unistd.h>
#include <fcntl.h>
#define OUT STDOUT_FILENO
#define ERR STDERR_FILENO
int main()
{
int handle, pid;
char ch;
if((handle = open("temp", O_CREAT|O_RDWR|O_TRUNC, S_IREAD|S_IWRITE)) < 0)
{
write(ERR, "open\n", 5);
exit(0);
}
if((pid = fork()) < 0)
{
write(ERR, "fork\n", 5);
exit(0);
}
else if(pid)
{
for(ch = 'a'; ch <= 'z'; ch++)
write(handle, &ch, 1);
}
else
{
char *file[3];
sprintf(file, "%d", handle);
execlp("./child", file, (char *) NULL);
}
close(handle);
exit(0);
}
child.c:
Code:
#include <unistd.h>
#include <fcntl.h>
#define OUT STDOUT_FILENO
#define ERR STDERR_FILENO
int main(int argc, char **argv)
{
int count = 0;
int input = atoi(argv[0]);
char buf;
int temp;
while(count < 26)
{
if((temp = read(input, &buf, 1)) < 0)
{
write(ERR, "write\n", 6);
exit(0);
}
if(temp)
{
write(OUT, &buf, 1);
count++;
}
}
exit(0);
}
The child process just goes into an imfinite loop, which indicates that read is always return 0. When I used pipes, everything worked fine. Please help me out. Thanks.