Created
November 9, 2016 15:11
-
-
Save Merovius/2c0da7d32e574704fdeabf644b1cb677 to your computer and use it in GitHub Desktop.
Demonstrate that stdin/stdout/stderr are only conventions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
// Demonstrate, that stdin, stdout, stderr are only conventional. We run a child | |
// process which doesn't have them open and open a random file to demonstrate, | |
// that it will just use one of those numbers. | |
// | |
// Works only under linux (but same principles apply on other unices) and needs | |
// to be started without parameters. | |
int main(int argc, char **argv) { | |
if (argc > 1) { | |
// Let's just open any file we know exists. | |
int fd = open("/tmp", O_RDONLY); | |
// We need to somehow signal what this new opened file has as an fd. We | |
// can't print, as stdout is potentially closed, so we use the exit status | |
// instead to signal an int to the parent, which will then print it. | |
return fd; | |
} | |
// Fork off a child process. | |
if (fork() == 0) { | |
// Close stdin, stdout, stderr. You can see the effect of closing only some | |
// of them by commenting these lines out partly. | |
close(0); | |
close(1); | |
close(2); | |
// Self-exec (only works under linux). Pass a parameter, so that the child | |
// knows it's the child | |
execl("/proc/self/exe", argv[0], "-child", NULL); | |
// Should never be reached. If exit code is 255, something went wrong. | |
return 255; | |
} | |
// Wait for child to exit and print exit status. | |
int status; | |
wait(&status); | |
printf("%d\n", WEXITSTATUS(status)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment