LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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.

Notices

Reply
 
LinkBack Search this Thread
Old 10-02-2006, 04:51 AM   #1
socialjazz
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, 08:55 AM   #2
KenJackson
Member
 
Registered: Jul 2006
Location: Maryland, USA
Distribution: Fedora, Arch
Posts: 568

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

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

Rep: Reputation: 108Reputation: 108
Note however that "cd" is special. This will not work as you might expect:
Code:
#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:
Code:
#include <unistd.h>
/* ... */
chdir("/tmp");
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.
 
  


Reply


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
Trackbacks are Off
Pingbacks are On
Refbacks are Off


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


All times are GMT -5. The time now is 10:32 AM.

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