Support LQ: Use code LQ3 and save $3 on Domain Registration
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 10-02-2006, 05:51 AM   #1
LQ Newbie
Registered: Sep 2006
Posts: 9

Rep: Reputation: 0
Executing command line through Code

Hi, can anyone give me a short code on how to execute command line such as "sh", "cd" etc using C programming code?

Thanks in advance
Old 10-02-2006, 09:55 AM   #2
Registered: Jul 2006
Location: Maryland, USA
Distribution: Fedora, PCLinuxOS
Posts: 582

Rep: Reputation: 65
Not sure if this is what you want, but try man system.

#include <stdlib.h>
int system(const char *command);
Old 10-02-2006, 04:09 PM   #3
Senior Member
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: ubuntu
Posts: 2,530

Rep: Reputation: 110Reputation: 110
Note however that "cd" is special. This will not work as you might expect:
#include <stdlib.h>
/* ... */
system("cd /tmp");
What happens is that system runs "sh" to do "cd". But "sh" is running in a seperate process, and every process has its own working directory. So after after the command ("cd") is executed, the "sh" process that ran it exits and the new working directory is lost.

To change the working directory from a C program, this will work:
#include <unistd.h>
/* ... */
This is the case for all shell-builtin's (and environment variables BTW). This is also the reason why the "cd" command is always a builtin command of any shell.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
posting code from command line frankie_DJ Linux - Newbie 3 08-09-2005 09:51 AM
Problem executing from command line jleyba213 Linux - General 4 04-09-2004 01:43 PM
executing from command line nodger Linux - Newbie 3 01-20-2004 11:30 AM
PostgreSQL: executing a .SQL file from command line? J_Szucs Linux - Software 0 09-25-2003 12:49 AM
Add lines of code to files from command line robeb Linux - General 2 06-12-2002 04:54 AM

All times are GMT -5. The time now is 08:58 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration