Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!sdd.hp.com!zaphod.mps.ohio-state.edu!rpi!uupsi!njin!rutgers!att!dptg!mtune!jrw From: jrw@mtune.ATT.COM (Jim Webb) Newsgroups: comp.unix.internals Subject: Re: How to know your current shell from C code Message-ID: <791@mtune.ATT.COM> Date: 17 Sep 90 17:31:28 GMT References: <1990Sep11.164436.9592@cadence.com> Distribution: usa Organization: AT&T BL Middletown/Lincroft NJ USA Lines: 61 In article , josef@nixpbe.UUCP (Moellers) writes: > In <1990Sep11.164436.9592@cadence.com> mikel@cadence.cadence.com writes: > > > > Recently I had a UNIX question. I have a c program and > >I want to know which shell(sh,csh,ksh) is my parent. Is there > >any way to do this? Environment variable is not acceptable. > > Quick'n'dirty: > ... > ppid = getppid() > ps = popen("ps", "r"); Since you know the parent's pid, why don't you pass it on the the ps command? Ergo: char psbuf[20]; sprintf(psbuf,"/bin/ps -p%d",getppid()); ps = popen(psbuf, "r"); > fgets(line, 80, ps); /* skip "PID TTY TIME COMMAND" */ > shell = (char *) 0; Doing this, you don't need to "grep" thru the output to find the process as you do here: > while (fgets(line, 80, ps) != NULL) > { > pspid = atoi(line); > if (pspid == ppid) > { > shell = line+22; <--------------------------+ > break; | > } | > } | | > shell[strlen(shell)-1] = '\0'; | | You really ought to do the above line AFTER making sure that some | was assigned to it :-) Like right here instead ---------------------+ Granted, in this case all it would probably do is write a \0 into line[79], but it still is a bad practice to get into, especially since you test for errors later on here: > if (shell == (char *) 0) > printf("Huh??"); > else > printf("Your friendly neighbourhood shell is \"%s\"\n", shell); Another thing you might want to clobber out is the - at the begining of login shells (eg -sh): if (*shell == '-') shell++; ps I just hope this isn't going into a set[u|g]id program, popen()'s are quite scary in that case..... -- Jim Webb "Out of Phase -- Get Help" att!mtune!jrw "I'm bored with this....Let's Dance!"