How to know your current shell from C code
Jim Webb
jrw at mtune.ATT.COM
Tue Sep 18 03:31:28 AEST 1990
In article <josef.653134656 at peun11>, josef at nixpbe.UUCP (Moellers) writes:
> In <1990Sep11.164436.9592 at cadence.com> mikel at 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!"
More information about the Comp.unix.internals
mailing list