2
我試圖給我的程序一個命令行參數,剝離第一個字符並將剩餘的字符串轉換爲int。但是當我用if (argv[i][0] == 'w')
進行測試時,我得到了分段錯誤。測試字符串中的第一個字符給出分段錯誤
$ ./program w10
Segmentation fault
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <argp.h>
#include <python2.7/Python.h>
/* If this flag is nonzero, don’t handle the signal right away. */
volatile sig_atomic_t signal_pending;
/* This is nonzero if a signal arrived and was not handled. */
volatile sig_atomic_t defer_signal;
void
huphandler (int signum)
{
if (defer_signal)
signal_pending = signum;
else
exit(0);
}
int
main(int argc, char **argv)
{
signal(SIGHUP, huphandler);
int i;
int wait = 0;
char *args[argc+3];
args[0] = "mypy.py";
for (i=0; i<argc; i++) {
if (argv[i][0] == 'w') { // Here's where the problem is
memmove(argv[i], argv[i]+1, strlen(argv[i]));
wait = strtol(argv[i], NULL, 10);
}
else {
args[i+1] = argv[i];
printf("%s\n", args[i+1]);
}
}
argc = i + 2;
FILE *file;
Py_SetProgramName(args[0]);
Py_Initialize();
PySys_SetArgv(argc, args);
while (true) {
defer_signal++;
file = fopen(strcat(getenv("HOME"), "/mypy.py"), "r");
PyRun_SimpleFile(file, "mypy.py");
Py_Finalize();
defer_signal--;
if (defer_signal == 0 && signal_pending != 0)
exit(0);
if (wait > 0) sleep(wait);
else exit(0);
}
}
你爲什麼試圖將argv [i]的值改爲1(並試圖寫出可能(幾乎肯定是)只讀內存)而不是僅僅增加argv [i]? –
是的,我已將它更改爲'argv [i] ++;'。我只是不確定。但它仍然失敗。 – user193661
發佈的代碼缺少聲明:'#include',這是'strtol()'和'memmove()'和'strlen()'和'strcat()'函數需要的。發佈的代碼缺少以下語句:'exit()'和'getenv()'函數需要'#include ' –
user3629249