是否有Windows(Visual C)的unistd.h替代品?

2024-04-19 11:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将一个为Unix编写的相对简单的控制台程序移植到Windows平台(Visual C++ 8.0)。所有源文件都包含“unistd.h”,但它并不存在。删除它,我会收到关于“srandom”、“random”和“getopt”的错误原型的投诉。 我知道我可以替换随机函数,而且我非常确定我可以找到/破解getopt实现。

但我相信其他人也遇到了同样的挑战。 我的问题是:Windows有“unistd.h”端口吗?至少有一个包含那些具有本机Windows实现的函数-我不需要管道或分叉。

编辑

我知道我可以创建自己的“unistd.h”,其中包含我需要的东西的替代品-特别是在这种情况下,因为它是一个有限集。但由于这似乎是一个常见的问题,我想知道是否有人已经为更大的功能子集做了这项工作。

切换到不同的编译器或环境在工作中是不可能的-我被Visual Studio困住了。


Tags: 端口函数程序windows错误unixrandom平台
3条回答

尝试包含io.h文件。它似乎相当于Visual Studio的unistd.h

我希望这能有帮助。

由于在Internet上找不到版本,我们从这里开始。
大多数到Windows的端口可能只需要完整Unix文件的一个子集。
这是一个起点。请根据需要添加定义。

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as neeeded.
 * https://stackoverflow.com/a/826027/1202830
 */

#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */

#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t; 
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */

我建议使用mingw/msys作为开发环境。尤其是在移植简单的控制台程序时。Msys在Windows上实现了一个类Unix的shell,mingw是GNU compiler collection (GCC)和其他GNU构建工具到Windows平台的端口。它是一个开源项目,非常适合这个任务。我目前使用它来为Windows XP构建实用程序和控制台应用程序,而且它肯定有您正在寻找的unistd.h头。

安装过程可能有点棘手,但我发现最好从MSYS开始。

相关问题 更多 >