Skip to content

Instantly share code, notes, and snippets.

@goyusia
Created December 15, 2015 08:01
Show Gist options
  • Select an option

  • Save goyusia/98797d8cc84ef3e2685c to your computer and use it in GitHub Desktop.

Select an option

Save goyusia/98797d8cc84ef3e2685c to your computer and use it in GitHub Desktop.
fork with stdout buffer
// https://twitter.com/RhoP_nim/status/676667506052825090
#include "apue.h"
int glob = 6;
char buf[] = "a write to stdout\n";
void err_sys(const char *x, ...)
{
perror(x);
exit(1);
}
int main(void)
{
int var;
pid_t pid;
var = 88;
if(write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1) err_sys("write error");
printf("before fork\n");
/* added */
fflush(stdout);
if((pid = fork()) < 0) {
err_sys("fork error");
} else if(pid == 0) {
glob++;
var++;
} else {
sleep(2);
}
printf("pid = %d, glod = %d, var = %d\n", getpid(), glob, var);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment