[英]issue executing unix commands using system() in c
我目前正在嘗試編寫一個程序來接受用戶輸入並在 unix 系統中執行命令,代碼可以編譯,但是當我運行它時出現分段錯誤。 我認為它可能與 system() 函數的輸入數據類型有關,但我似乎無法弄清楚
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
char argument[1024];
main() {
fgets(argument, 1024, stdin);
strtok (argument, "\n");
char *command = strcat("cd ", argument);
int response = system(command);
if(response == -1)
{
printf("error executing command");
}
}
如果這看起來微不足道,我深表歉意我對 c 沒有太多經驗
您正在 Unix 系統中使用 C 進行編程。
編寫 C 語言只是為了編寫 Unix 本身。 system()
是用 C、Unix、Windows、Linux、Android、MacOS、Python、java 編寫的,所有的東西最初都是用 C 編寫的,而且大部分仍然是用 C 編寫的。 並且您在 Unix 和衍生產品中有許多shells
,它們只在用戶鍵入命令時運行命令。 所以使用system()
來運行一個命令並沒有增加太多。 只是另一個間接級別,一個很大的安全漏洞,因為您的程序可能會被不太好的人用來做意想不到的事情。 使用您的程序。
這是下面程序的輸出
Current directory is: /home/testing/projects/tcursor
directory changed to '/tmp'
Enter name of directory to create: thing
'/tmp/thing' created
Now changing to newly created folder
Current directory is: '/tmp/thing'
節目剛剛
cwd
到/tmp
cd
到它 所以你可以看到一些 C 代碼到cd
, pwd
和mkdir
int main(void)
{
char asw[30];
char buffer[1024];
char* p = buffer;
const char* temp = "/tmp";
p = getcwd(p,1024);
printf("Current directory is: %s\n",p);
int n = chdir(temp);
if ( n != 0 ) return(1);
printf("directory changed to '%s'\n", temp);
printf("Enter name of directory to create: ");
fgets(asw,30,stdin);
asw[strlen(asw)-1] = 0;
n = mkdir(asw, 0777 );
if ( n != 0 ) return(2);
printf("'%s' created\n", buffer);
printf("Now changing to newly created folder\n");
sprintf(buffer,"%s/%s", temp, asw);
n = chdir(buffer);
if ( n != 0 ) return(4);
p = getcwd(p,1024);
printf("Current directory is: '%s'\n",p);
return 0;
不要使用system()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.