sps*_*sps 2 c linux hardlink execvp
我们知道我们可以在Linux中创建硬链接,ln file1 file2这将成为file2一个硬链接file1.
但是,当我尝试使用C程序执行此操作时,我遇到了问题.下面是C代码.
#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
if ((strcmp (argv[1],"ln")) == 0 )
{
char *myargs[4];
myargs[0] = "ln";
myargs[1] = argv[3];
myargs[2] = argv[4];
myargs[3] = NULL;
execvp(myargs[0], myargs);
printf("Unreachable code\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用gcc编译这个程序后,我按如下方式运行它.
$ ./a.out ln file1 file2
ln: failed to access ‘file2’: No such file or directory
$
Run Code Online (Sandbox Code Playgroud)
这里file1存在并且file2是期望的硬链接.
任何人都可以指出我在哪里弄错了.
谢谢.
Shell脚本知识很少能很好地转移到C编程.以下是man 2 link您应该使用的内容:
NAME
link - make a new name for a file
SYNOPSIS
#include <unistd.h>
int link(const char *oldpath, const char *newpath);
Run Code Online (Sandbox Code Playgroud)
使用C api而不是外部shell工具的好处包括显着的性能提升和标志注入的消除.