Having in mind to communicate with a multi-client Unix domain socket without keyboard input, I want to create a file descriptor that replaces stdin.
With a multi-client socket, you have to add the stdin's file descriptor (which is 0, with FD_SET(0, &readfds)
) to readfds in order to send the keyboard input (FD_ISSET(0, &readfds)
) to the server. Since I don't want to write everytime I launch my client, I want to replace this file descriptor by a custom one (by writing to this file from another program).
I checked out Create a file descriptor to create two programs:
One that writes to the file descriptor:
int main() {
char buffer[] = "test";
int fd = open("sample.dat", O_WRONLY | O_CREAT, 0666);
dup2(fd, 5);
if(write(5, buffer, 4) < 0)
fprintf(stderr, "write %s\n", strerror(errno));
close(5);
return 0;
}
And another one that reads from it:
int main() {
char buffer[4];
int fd = open("sample.dat", O_RDONLY);
dup2(fd, 5);
for(;;) {
if(read(5, buffer, 4) < 0)
fprintf(stderr, "read %s\n", strerror(errno));
printf("%s\n", buffer);
sleep(1);
}
return 0;
}
My question is: is it possible to make this file descriptor as stdin-like ? I mean actually my second program read "test" endlessly because (of course) sample.dat still contains "test" but I want to delete it once it has been read.