在 Ubuntu 中创建一个文件作为 C 中的可执行程序

Create a file as executable program in C in Ubuntu

本文关键字:文件 可执行程序 一个 创建 Ubuntu      更新时间:2023-10-16

我的程序通过TCP套接字接收一个可执行的二进制文件。

我需要将此文件作为可执行程序保存到硬盘中。已成功接收文件,但问题是默认文件属性设置为不可执行。

如何在 Ubuntu 中将文件的属性更改为 C 中的可执行文件?

谢谢问候机器人

int chmod(const char *path, mode_t mode)int fchmod(int fd, mode_t mode) ? 怎么样

apropos chmod
man 2 chmod

最基本的例子:

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
   char * fpath = "/path/to/binary";
   int ret=0;
   if(ret = chmod(fpath, S_IRUSR|S_IXUSR) < 0){
      perror("chmod failed");
      exit(1);
   }
   printf("chmod okn");
   exit(0);
}

您如何创建和写入文件? 如果您知道它将是可执行的,请首先使用正确的模式制作文件。

int fd = open("path/to/file", O_WRONLY | O_CREAT, 0777);

除非umask剥离可执行位(通用值是00220002,其中不保留可执行位),否则path/to/file最初将创建可执行文件。

您可以使用

chmod更改文件模式。有关详细信息,请阅读手册页( man 2 chmod )(与 shell 命令chmod大致相同)。