我正在尝试打印系统的所有组(Ubuntu 20.04(:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>
int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:nn");
struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);
endgrent();
exit(EXIT_SUCCESS);
}
我用sudo
运行程序,得到:
$ sudo ./program
Here are all of this system's groups:
Segmentation fault
使用struct spwd
时也会发生同样的错误。
更新
我用include
行更新了源代码,并省略了lib/*.c
部分。当我编译这段代码时:
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: [...]
Thread model: posix
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
$ gcc -std=c17 main.c -o program
main.c: In function ‘main’:
main.c:11:18: warning: implicit declaration of function ‘getgrent’ [-Wimplicit-function-declaration]
11 | while ((grp = getgrent()) != NULL)
| ^~~~~~~~
main.c:11:16: warning: assignment to ‘struct group *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
11 | while ((grp = getgrent()) != NULL)
| ^
main.c:14:4: warning: implicit declaration of function ‘endgrent’ [-Wimplicit-function-declaration]
14 | endgrent();
| ^~~~~~~~
当我运行它时:
$ ./program
Here are all of this system's groups:
Segmentation fault (core dumped)
$ sudo ./program
Here are all of this system's groups:
Segmentation fault
现在,当我运行VS代码调试器时,它可以正常工作。VS代码是根据本文配置的。
这是我的launch.json
:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc-9 - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc-9 build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
添加正确的标头:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>
int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:nn");
struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);
endgrent();
exit(EXIT_SUCCESS);
}
更新:-std=c17
很奇怪,它没有包括<grp.h>
。您可能需要std=gnu17
,其中包括一些gnu+posix的内容。