在Linux中用 exec 函数创建一个进程,显示当前目录下的文件信息。
时间: 2024-05-09 21:20:16 浏览: 8
以下是一个用 exec 函数创建进程并显示当前目录下文件信息的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
char *args[] = { "/bin/ls", "-l", NULL };
if (execvp(args[0], args) == -1) {
perror("exec error");
exit(EXIT_FAILURE);
}
} else {
// Parent process
wait(NULL);
printf("Child process finished.\n");
}
return 0;
}
```
在上面的代码中,我们使用 fork 函数创建了一个子进程,然后在子进程中用 execvp 函数执行了 ls 命令,并传入了参数 "-l",以显示当前目录下的文件信息。在父进程中,我们使用 wait 函数等待子进程执行完毕,然后输出一条提示信息。
相关问题
Linux中用shell程序将一目录拷贝在另外一个目录下
你可以使用 shell 程序编写一个脚本来实现将一个目录拷贝到另一个目录。
下面是一个简单的示例脚本,将 `/path/to/source/directory` 目录拷贝到 `/path/to/destination/directory` 目录下:
```
#!/bin/bash
# 源目录和目标目录
src_dir=/path/to/source/directory
dest_dir=/path/to/destination/directory
# 判断目标目录是否存在,不存在则创建
if [ ! -d "$dest_dir" ]; then
mkdir -p "$dest_dir"
fi
# 复制目录
cp -r "$src_dir" "$dest_dir"
```
请将 `/path/to/source/directory` 替换为要复制的源目录路径,将 `/path/to/destination/directory` 替换为目标目录路径。注意,如果目标目录已经存在,那么复制的内容将会被覆盖。如果你希望在目标目录下创建一个新的子目录来存放源目录的内容,可以在目标目录路径后面加上一个新的目录名。
Linux中用shell将一目录拷贝在另外一个目录下
你可以使用 `cp` 命令来实现将一个目录拷贝到另一个目录。具体的命令如下:
```
cp -r /path/to/source/directory /path/to/destination/directory
```
其中,`-r` 参数表示递归地复制整个目录。请将 `/path/to/source/directory` 替换为要复制的源目录路径,将 `/path/to/destination/directory` 替换为目标目录路径。注意,如果目标目录已经存在,那么复制的内容将会被覆盖。如果你希望在目标目录下创建一个新的子目录来存放源目录的内容,可以在目标目录路径后面加上一个新的目录名。