Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
freem
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Openai/6911cc4b-5d54-800b-88ae-dc7ac6ff2d3d
(section)
Add languages
Page
Discussion
English
Read
Edit
Edit source
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
Edit source
View history
General
What links here
Related changes
Special pages
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==== 原则: 尽量不要把字符串交给 shell;使用 exec 系列(或 posix_spawn)以参数数组形式传递参数,让操作系统直接运行可执行文件,而不是通过 shell 解析。 ==== ===== <syntaxhighlight lang="c">#include <stdio.h> ===== #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { pid_t pid; char *cmd = "/bin/ls"; char *args[3]; if (argc < 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); return 1; } pid = fork(); if (pid < 0) { perror("fork"); return 1; } if (pid == 0) { /* 子进程直接把用户输入作为参数传给 ls。 execvp 不会经过 shell,因此不会解释 ; && 等元字符 */ args[0] = "ls"; args[1] = argv[1]; /'' 来自用户的字符串,但作为单一参数 ''/ args[2] = NULL; execvp(cmd, args); /'' execvp 失败才会执行下面 ''/ perror("execvp"); _exit(127); } else { /'' 父进程等待子进程结束(可选) ''/ wait(NULL); } return 0; } </syntaxhighlight> execvp 使用参数向量(argv),不会让 shell 解析参数里的元字符,因此避免了注入路径。
Summary:
Please note that all contributions to freem are considered to be released under the Creative Commons Attribution-ShareAlike 4.0 (see
Freem:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)