_popen_wpopen

创建一个管道并执行命令。

重要

此 API 不能用于在 Windows 运行时中执行的应用程序。 有关详细信息,请参阅通用 Windows 平台应用中不支持的 CRT 函数

语法

FILE *_popen(
    const char *command,
    const char *mode
);
FILE *_wpopen(
    const wchar_t *command,
    const wchar_t *mode
);

参数

command
要执行的命令。

mode
返回流的模式。

返回值

返回一个与创建的管道一端相关联的流。 管道的另一端与生成的命令的标准输入或标准输出相关联。 函数针对错误返回 NULL。 如果错误是由无效参数引起的,则将 errno 设置为 EINVAL。 有关有效模式的信息,请参阅“备注”部分。

有关这些和其他错误代码的信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

备注

函数 _popen 创建一个管道。 然后,它会异步执行命令处理器的生成副本,并将 command 用作命令行。 字符串 mode 指定请求的访问类型,如下所示。

访问模式 说明
"r" 调用进程可使用返回的流读取生成的命令的标准输出。
"w" 调用进程可使用返回的流写入生成的命令的标准输入。
"b" 在二进制模式下打开。
"t" 在文本模式下打开。

注意

如果在 Windows 程序中使用,_popen 函数将返回可导致程序无限期停止响应的无效文件指针。 _popen 在控制台应用程序中正常工作。 若要创建重定向输入和输出的 Windows 应用程序,请参阅 Windows SDK 中的创建具有重定向输入和输出的子进程

_wpopen_popen的宽字符版本; path_wpopen 参数是宽字符字符串。 除此以外,_wpopen_popen 的行为完全相同。

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

Tchar.h 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tpopen _popen _popen _wpopen

要求

例程 必需的标头
_popen <stdio.h>
_wpopen <stdio.h><wchar.h>

有关兼容性的详细信息,请参阅 兼容性

C 运行时库的所有版本。

示例

// popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char psBuffer[128];
    FILE* pPipe;

    /* Run DIR so that it writes its output to a pipe. Open this
     * pipe with read text attribute so that we can read it
     * like a text file.
     */

    if ((pPipe = _popen("dir *.c /on /p", "rt")) == NULL)
    {
        exit(1);
    }

    /* Read pipe until end of file, or an error occurs. */

    while (fgets(psBuffer, 128, pPipe))
    {
        puts(psBuffer);
    }

    int endOfFileVal = feof(pPipe);
    int closeReturnVal = _pclose(pPipe);

    if (endOfFileVal)
    {
        printf("\nProcess returned %d\n", closeReturnVal);
    }
    else
    {
        printf("Error: Failed to read the pipe to the end.\n");
    }
}

此输出假定当前目录中只有一个文件扩展名为 .c 的文件。

Volume in drive C is CDRIVE
Volume Serial Number is 0E17-1702

Directory of D:\proj\console\test1

07/17/98  07:26p                   780 popen.c
               1 File(s)            780 bytes
                             86,597,632 bytes free

Process returned 0

另请参阅

进程和环境控制
_pclose
_pipe