Path: utzoo!mnetor!uunet!lll-winken!lll-lcc!ames!pasteur!ucbvax!cbosgd!cbdkc1!pmd From: pmd@cbdkc1.ATT.COM (Paul Dubuc) Newsgroups: comp.lang.c Subject: Re: system (and mkdir) Message-ID: <2771@cbdkc1.ATT.COM> Date: 20 Jan 88 20:26:48 GMT References: <127@dcrbg1.UUCP> <9472@ccicpg.UUCP> Reply-To: pmd@cbdkc1.UUCP (Paul Dubuc) Organization: AT&T Bell Laboratories; Columbus, Ohio Lines: 50 Keywords: c program In article <9472@ccicpg.UUCP> miket@ccicpg.UUCP (Mike Tracy) writes: }In article <127@dcrbg1.UUCP> bcf2303@dcrbg1.UUCP (Wing Chow) writes: }> }>can someone give me an example of how to use 'system' in a c program? } }The best example I have is the mkdir command. Since a normal }user can not create a directory. The mkdir (under Unix) is a SUID root }program. That is, when the program is envoked its effective user id is }that of the super user (stupid user :-)) root. } }To make a directory from you C program (unless your program is }SUID root) you must use the system call (with the appropriate checks }for success). } } system( "mkdir mydir" ); No, you don't have to you system() for this. You can use fork()/exec(). See my previous article on this subject. For the reasons I gave in that article, system() is best reserved for running command strings that need the facilities of the shell (pipelines, redirection, metacharacter translation, etc.). However, running mkdir from a C program either way brings up an interesting example of another problem. Suppose I (pmd) have a program that runs set-uid to user 'joe'. This program exec's mkdir to create a directory. If it then tries to change the mode, owner or group on the directory it just created, it can't. Why? Because mkdir runs set-uid to root, creates the directory and then sets the owner to the real user ID of the process (pmd in my case). My program is running as 'joe' and can't change the mode, owner or group on any directory it creates because it is not the owner (and not 'root' either). This is a problem because it's good practice for programs that create directories to be selective about the permissions of those directories and the lack of a solution means your program may be "broken" by merely setting the set-uid bit*. It's also a needless security risk to make the program set-uid to root just to avoid this problem. I know how much readers of this group like puzzles, so I won't detail the solution (it's fairly simple, anyway). For my solution, I implemented a mkdir() subroutine that runs the mkdir command (with fork() and exec(), not system()) and takes mode, owner and group specifications as arguments, so the whole proceedure is isolated to one routine. This allows a safe, easy way to create directories independent of the real or effective user ID of the calling process. -- * The set-uid bit is patented by Dennis Ritchie. -- Paul Dubuc {ihnp4,cbosgd}!cbdkc1!pmd