Added a basic implementation of wc.
[4chanprog.git] / coreutils / nohup.c
blobf06dff450a79baf6249948ffbcebcf2ef5feff97
1 /* @nohup.c */
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
12 int main(int argc, char **argv) {
13 int outfd,tty_1,tty_2;
15 if(argc<2) {
16 fprintf(stderr,"usage: %s utility [args...]\n",argv[0]);
17 return 127;
19 tty_1=isatty(1);
20 tty_2=isatty(2);
21 if(tty_1 || tty_2) {
22 outfd=open("nohup.out",O_APPEND|O_CREAT|O_WRONLY,S_IRUSR|S_IWUSR);
23 if(outfd==-1) {
24 char *filepath;
25 char *homedir=getenv("HOME");
26 if(!homedir) {
27 fprintf(stderr,"%s: cannot get value of $HOME\n",argv[0]);
28 return 127;
30 if(!(filepath=malloc(strlen(homedir)+11))) {
31 fprintf(stderr,"%s: out of memory\n",argv[0]);
32 return 127;
34 strcpy(filepath,homedir);
35 strcat(filepath,"/nohup.out");
36 outfd=open(filepath,O_APPEND|O_CREAT|O_WRONLY,S_IRUSR|S_IWUSR);
37 free(filepath);
38 if(outfd==-1) {
39 fprintf(stderr,"%s: cannot create %s/nohup.out\n",argv[0],homedir);
40 return 127;
43 if(tty_2 && dup2(outfd,2)==-1) {
44 fprintf(stderr,"%s: cannot redirect stderr: %s\n",argv[0],strerror(errno));
45 return 127;
47 if(tty_1 && dup2(outfd,1)==-1) {
48 fprintf(stderr,"%s: cannot redirect stdout: %s\n",argv[0],strerror(errno));
49 return 127;
52 signal(SIGHUP, SIG_IGN);
53 execvp(argv[1], argv + 1);
54 fprintf(stderr, "%s: cannot exec `%s': %s\n",argv[0],argv[1],strerror(errno));
55 if(errno==ENOENT)
56 return 127;
57 return 126;