2 /* POSIX module implementation */
4 /* This file is also used for Windows NT/MS-Win and OS/2. In that case the
5 module actually calls itself 'nt' or 'os2', not 'posix', and a few
6 functions are either unimplemented or implemented differently. The source
7 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
8 of the compiler used. Different compilers define their own feature
9 test macro, e.g. '__BORLANDC__' or '_MSC_VER'. For OS/2, the compiler
10 independent macro PYOS_OS2 should be defined. On OS/2 the default
11 compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
12 as the compiler specific macro for the EMX port of gcc to OS/2. */
14 /* See also ../Dos/dosmodule.c */
18 * Step 1 of support for weak-linking a number of symbols existing on
19 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
20 * at the end of this file for more information.
24 # pragma weak fstatvfs
26 #endif /* __APPLE__ */
28 #define PY_SSIZE_T_CLEAN
31 #include "structseq.h"
35 #endif /* defined(__VMS) */
41 PyDoc_STRVAR(posix__doc__
,
42 "This module provides access to operating system functionality that is\n\
43 standardized by the C Standard and the POSIX standard (a thinly\n\
44 disguised Unix interface). Refer to the library manual and\n\
45 corresponding Unix manual entries for more information on calls.");
47 #ifndef Py_USING_UNICODE
48 /* This is used in signatures of functions. */
49 #define Py_UNICODE void
54 #define INCL_DOSERRORS
55 #define INCL_DOSPROCESS
67 #ifdef HAVE_SYS_TYPES_H
68 #include <sys/types.h>
69 #endif /* HAVE_SYS_TYPES_H */
71 #ifdef HAVE_SYS_STAT_H
73 #endif /* HAVE_SYS_STAT_H */
75 #ifdef HAVE_SYS_WAIT_H
76 #include <sys/wait.h> /* For WNOHANG */
85 #endif /* HAVE_FCNTL_H */
91 #ifdef HAVE_SYSEXITS_H
93 #endif /* HAVE_SYSEXITS_H */
95 #ifdef HAVE_SYS_LOADAVG_H
96 #include <sys/loadavg.h>
99 /* Various compilers have only certain posix functions */
100 /* XXX Gosh I wish these were all moved into pyconfig.h */
101 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
104 #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
105 #define HAVE_GETCWD 1
106 #define HAVE_OPENDIR 1
107 #define HAVE_SYSTEM 1
114 #ifdef __BORLANDC__ /* Borland compiler */
116 #define HAVE_GETCWD 1
117 #define HAVE_OPENDIR 1
120 #define HAVE_SYSTEM 1
123 #ifdef _MSC_VER /* Microsoft compiler */
124 #define HAVE_GETCWD 1
125 #define HAVE_SPAWNV 1
129 #define HAVE_SYSTEM 1
132 #define fsync _commit
134 #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
135 /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
136 #else /* all other compilers */
137 /* Unix functions that the configure script doesn't check for */
140 #if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
143 #define HAVE_GETCWD 1
144 #define HAVE_GETEGID 1
145 #define HAVE_GETEUID 1
146 #define HAVE_GETGID 1
147 #define HAVE_GETPPID 1
148 #define HAVE_GETUID 1
150 #define HAVE_OPENDIR 1
155 #define HAVE_SYSTEM 1
157 #define HAVE_TTYNAME 1
158 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */
159 #endif /* _MSC_VER */
160 #endif /* __BORLANDC__ */
161 #endif /* ! __WATCOMC__ || __QNX__ */
162 #endif /* ! __IBMC__ */
166 #if defined(__sgi)&&_COMPILER_VERSION>=700
167 /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
169 extern char *ctermid_r(char *);
172 #ifndef HAVE_UNISTD_H
173 #if defined(PYCC_VACPP)
174 extern int mkdir(char *);
176 #if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
177 extern int mkdir(const char *);
179 extern int mkdir(const char *, mode_t
);
182 #if defined(__IBMC__) || defined(__IBMCPP__)
183 extern int chdir(char *);
184 extern int rmdir(char *);
186 extern int chdir(const char *);
187 extern int rmdir(const char *);
190 extern int chmod(const char *, int);
192 extern int chmod(const char *, mode_t
);
194 extern int chown(const char *, uid_t
, gid_t
);
195 extern char *getcwd(char *, int);
196 extern char *strerror(int);
197 extern int link(const char *, const char *);
198 extern int rename(const char *, const char *);
199 extern int stat(const char *, struct stat
*);
200 extern int unlink(const char *);
201 extern int pclose(FILE *);
203 extern int symlink(const char *, const char *);
204 #endif /* HAVE_SYMLINK */
206 extern int lstat(const char *, struct stat
*);
207 #endif /* HAVE_LSTAT */
208 #endif /* !HAVE_UNISTD_H */
210 #endif /* !_MSC_VER */
214 #endif /* HAVE_UTIME_H */
216 #ifdef HAVE_SYS_UTIME_H
217 #include <sys/utime.h>
218 #define HAVE_UTIME_H /* pretend we do for the rest of this file */
219 #endif /* HAVE_SYS_UTIME_H */
221 #ifdef HAVE_SYS_TIMES_H
222 #include <sys/times.h>
223 #endif /* HAVE_SYS_TIMES_H */
225 #ifdef HAVE_SYS_PARAM_H
226 #include <sys/param.h>
227 #endif /* HAVE_SYS_PARAM_H */
229 #ifdef HAVE_SYS_UTSNAME_H
230 #include <sys/utsname.h>
231 #endif /* HAVE_SYS_UTSNAME_H */
235 #define NAMLEN(dirent) strlen((dirent)->d_name)
237 #if defined(__WATCOMC__) && !defined(__QNX__)
239 #define NAMLEN(dirent) strlen((dirent)->d_name)
241 #define dirent direct
242 #define NAMLEN(dirent) (dirent)->d_namlen
244 #ifdef HAVE_SYS_NDIR_H
245 #include <sys/ndir.h>
247 #ifdef HAVE_SYS_DIR_H
262 #ifdef HAVE_PROCESS_H
267 #include <shellapi.h> /* for ShellExecute() */
269 #define pclose _pclose
270 #endif /* _MSC_VER */
272 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
277 #if defined(PATH_MAX) && PATH_MAX > 1024
278 #define MAXPATHLEN PATH_MAX
280 #define MAXPATHLEN 1024
282 #endif /* MAXPATHLEN */
285 /* Emulate some macros on systems that have a union instead of macros */
288 #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
292 #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
296 #define WTERMSIG(u_wait) ((u_wait).w_termsig)
299 #define WAIT_TYPE union wait
300 #define WAIT_STATUS_INT(s) (s.w_status)
302 #else /* !UNION_WAIT */
303 #define WAIT_TYPE int
304 #define WAIT_STATUS_INT(s) (s)
305 #endif /* UNION_WAIT */
307 /* Don't use the "_r" form if we don't need it (also, won't have a
308 prototype for it, at least on Solaris -- maybe others as well?). */
309 #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
310 #define USE_CTERMID_R
313 #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
317 /* choose the appropriate stat and fstat functions and return structs */
319 #if defined(MS_WIN64) || defined(MS_WINDOWS)
320 # define STAT win32_stat
321 # define FSTAT win32_fstat
322 # define STRUCT_STAT struct win32_stat
326 # define STRUCT_STAT struct stat
329 #if defined(MAJOR_IN_MKDEV)
330 #include <sys/mkdev.h>
332 #if defined(MAJOR_IN_SYSMACROS)
333 #include <sys/sysmacros.h>
335 #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
336 #include <sys/mkdev.h>
340 /* Return a dictionary corresponding to the POSIX environment table */
341 #ifdef WITH_NEXT_FRAMEWORK
342 /* On Darwin/MacOSX a shared library or framework has no access to
343 ** environ directly, we must obtain it with _NSGetEnviron().
345 #include <crt_externs.h>
346 static char **environ
;
347 #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
348 extern char **environ
;
349 #endif /* !_MSC_VER */
359 #ifdef WITH_NEXT_FRAMEWORK
361 environ
= *_NSGetEnviron();
365 /* This part ignores errors */
366 for (e
= environ
; *e
!= NULL
; e
++) {
369 char *p
= strchr(*e
, '=');
372 k
= PyString_FromStringAndSize(*e
, (int)(p
-*e
));
377 v
= PyString_FromString(p
+1);
383 if (PyDict_GetItem(d
, k
) == NULL
) {
384 if (PyDict_SetItem(d
, k
, v
) != 0)
390 #if defined(PYOS_OS2)
393 char buffer
[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
395 rc
= DosQueryExtLIBPATH(buffer
, BEGIN_LIBPATH
);
396 if (rc
== NO_ERROR
) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
397 PyObject
*v
= PyString_FromString(buffer
);
398 PyDict_SetItemString(d
, "BEGINLIBPATH", v
);
401 rc
= DosQueryExtLIBPATH(buffer
, END_LIBPATH
);
402 if (rc
== NO_ERROR
) { /* (not a typo, envname is NOT 'END_LIBPATH') */
403 PyObject
*v
= PyString_FromString(buffer
);
404 PyDict_SetItemString(d
, "ENDLIBPATH", v
);
413 /* Set a POSIX-specific error from errno, and return NULL */
418 return PyErr_SetFromErrno(PyExc_OSError
);
421 posix_error_with_filename(char* name
)
423 return PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
426 #ifdef Py_WIN_WIDE_FILENAMES
428 posix_error_with_unicode_filename(Py_UNICODE
* name
)
430 return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError
, name
);
432 #endif /* Py_WIN_WIDE_FILENAMES */
436 posix_error_with_allocated_filename(char* name
)
438 PyObject
*rc
= PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
445 win32_error(char* function
, char* filename
)
447 /* XXX We should pass the function name along in the future.
448 (_winreg.c also wants to pass the function name.)
449 This would however require an additional param to the
450 Windows error object, which is non-trivial.
452 errno
= GetLastError();
454 return PyErr_SetFromWindowsErrWithFilename(errno
, filename
);
456 return PyErr_SetFromWindowsErr(errno
);
459 #ifdef Py_WIN_WIDE_FILENAMES
461 win32_error_unicode(char* function
, Py_UNICODE
* filename
)
463 /* XXX - see win32_error for comments on 'function' */
464 errno
= GetLastError();
466 return PyErr_SetFromWindowsErrWithUnicodeFilename(errno
, filename
);
468 return PyErr_SetFromWindowsErr(errno
);
471 static PyObject
*_PyUnicode_FromFileSystemEncodedObject(register PyObject
*obj
)
475 /* Function suitable for O& conversion */
477 convert_to_unicode(PyObject
*arg
, void* _param
)
479 PyObject
**param
= (PyObject
**)_param
;
480 if (PyUnicode_CheckExact(arg
)) {
484 else if (PyUnicode_Check(arg
)) {
485 /* For a Unicode subtype that's not a Unicode object,
486 return a true Unicode object with the same data. */
487 *param
= PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(arg
),
488 PyUnicode_GET_SIZE(arg
));
489 return *param
!= NULL
;
492 *param
= PyUnicode_FromEncodedObject(arg
,
493 Py_FileSystemDefaultEncoding
,
495 return (*param
) != NULL
;
498 #endif /* Py_WIN_WIDE_FILENAMES */
502 #if defined(PYOS_OS2)
503 /**********************************************************************
504 * Helper Function to Trim and Format OS/2 Messages
505 **********************************************************************/
507 os2_formatmsg(char *msgbuf
, int msglen
, char *reason
)
509 msgbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
511 if (strlen(msgbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
512 char *lastc
= &msgbuf
[ strlen(msgbuf
)-1 ];
514 while (lastc
> msgbuf
&& isspace(Py_CHARMASK(*lastc
)))
515 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
518 /* Add Optional Reason Text */
520 strcat(msgbuf
, " : ");
521 strcat(msgbuf
, reason
);
525 /**********************************************************************
526 * Decode an OS/2 Operating System Error Code
528 * A convenience function to lookup an OS/2 error code and return a
529 * text message we can use to raise a Python exception.
532 * The messages for errors returned from the OS/2 kernel reside in
533 * the file OSO001.MSG in the \OS2 directory hierarchy.
535 **********************************************************************/
537 os2_strerror(char *msgbuf
, int msgbuflen
, int errorcode
, char *reason
)
542 /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
543 Py_BEGIN_ALLOW_THREADS
544 rc
= DosGetMessage(NULL
, 0, msgbuf
, msgbuflen
,
545 errorcode
, "oso001.msg", &msglen
);
549 os2_formatmsg(msgbuf
, msglen
, reason
);
551 PyOS_snprintf(msgbuf
, msgbuflen
,
552 "unknown OS error #%d", errorcode
);
557 /* Set an OS/2-specific error and return NULL. OS/2 kernel
558 errors are not in a global variable e.g. 'errno' nor are
559 they congruent with posix error numbers. */
561 static PyObject
* os2_error(int code
)
566 os2_strerror(text
, sizeof(text
), code
, "");
568 v
= Py_BuildValue("(is)", code
, text
);
570 PyErr_SetObject(PyExc_OSError
, v
);
573 return NULL
; /* Signal to Python that an Exception is Pending */
578 /* POSIX generic methods */
581 posix_fildes(PyObject
*fdobj
, int (*func
)(int))
585 fd
= PyObject_AsFileDescriptor(fdobj
);
588 Py_BEGIN_ALLOW_THREADS
592 return posix_error();
597 #ifdef Py_WIN_WIDE_FILENAMES
599 unicode_file_names(void)
601 static int canusewide
= -1;
602 if (canusewide
== -1) {
603 /* As per doc for ::GetVersion(), this is the correct test for
604 the Windows NT family. */
605 canusewide
= (GetVersion() < 0x80000000) ? 1 : 0;
612 posix_1str(PyObject
*args
, char *format
, int (*func
)(const char*))
616 if (!PyArg_ParseTuple(args
, format
,
617 Py_FileSystemDefaultEncoding
, &path1
))
619 Py_BEGIN_ALLOW_THREADS
620 res
= (*func
)(path1
);
623 return posix_error_with_allocated_filename(path1
);
630 posix_2str(PyObject
*args
,
632 int (*func
)(const char *, const char *))
634 char *path1
= NULL
, *path2
= NULL
;
636 if (!PyArg_ParseTuple(args
, format
,
637 Py_FileSystemDefaultEncoding
, &path1
,
638 Py_FileSystemDefaultEncoding
, &path2
))
640 Py_BEGIN_ALLOW_THREADS
641 res
= (*func
)(path1
, path2
);
646 /* XXX how to report both path1 and path2??? */
647 return posix_error();
652 #ifdef Py_WIN_WIDE_FILENAMES
654 win32_1str(PyObject
* args
, char* func
,
655 char* format
, BOOL (__stdcall
*funcA
)(LPCSTR
),
656 char* wformat
, BOOL (__stdcall
*funcW
)(LPWSTR
))
661 if (unicode_file_names()) {
662 if (!PyArg_ParseTuple(args
, wformat
, &uni
))
665 Py_BEGIN_ALLOW_THREADS
666 result
= funcW(PyUnicode_AsUnicode(uni
));
669 return win32_error_unicode(func
, PyUnicode_AsUnicode(uni
));
674 if (!PyArg_ParseTuple(args
, format
, &ansi
))
676 Py_BEGIN_ALLOW_THREADS
677 result
= funcA(ansi
);
680 return win32_error(func
, ansi
);
686 /* This is a reimplementation of the C library's chdir function,
687 but one that produces Win32 errors instead of DOS error codes.
688 chdir is essentially a wrapper around SetCurrentDirectory; however,
689 it also needs to set "magic" environment variables indicating
690 the per-drive current directory, which are of the form =<drive>: */
692 win32_chdir(LPCSTR path
)
694 char new_path
[MAX_PATH
+1];
698 if(!SetCurrentDirectoryA(path
))
700 result
= GetCurrentDirectoryA(MAX_PATH
+1, new_path
);
703 /* In the ANSI API, there should not be any paths longer
705 assert(result
<= MAX_PATH
+1);
706 if (strncmp(new_path
, "\\\\", 2) == 0 ||
707 strncmp(new_path
, "//", 2) == 0)
708 /* UNC path, nothing to do. */
710 env
[1] = new_path
[0];
711 return SetEnvironmentVariableA(env
, new_path
);
714 /* The Unicode version differs from the ANSI version
715 since the current directory might exceed MAX_PATH characters */
717 win32_wchdir(LPCWSTR path
)
719 wchar_t _new_path
[MAX_PATH
+1], *new_path
= _new_path
;
721 wchar_t env
[4] = L
"=x:";
723 if(!SetCurrentDirectoryW(path
))
725 result
= GetCurrentDirectoryW(MAX_PATH
+1, new_path
);
728 if (result
> MAX_PATH
+1) {
729 new_path
= malloc(result
);
731 SetLastError(ERROR_OUTOFMEMORY
);
735 if (wcsncmp(new_path
, L
"\\\\", 2) == 0 ||
736 wcsncmp(new_path
, L
"//", 2) == 0)
737 /* UNC path, nothing to do. */
739 env
[1] = new_path
[0];
740 result
= SetEnvironmentVariableW(env
, new_path
);
741 if (new_path
!= _new_path
)
748 /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
749 - time stamps are restricted to second resolution
750 - file modification times suffer from forth-and-back conversions between
752 Therefore, we implement our own stat, based on the Win32 API directly.
754 #define HAVE_STAT_NSEC 1
759 unsigned short st_mode
;
773 static __int64 secs_between_epochs
= 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
776 FILE_TIME_to_time_t_nsec(FILETIME
*in_ptr
, int *time_out
, int* nsec_out
)
778 /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
779 /* Cannot simply cast and dereference in_ptr,
780 since it might not be aligned properly */
782 memcpy(&in
, in_ptr
, sizeof(in
));
783 *nsec_out
= (int)(in
% 10000000) * 100; /* FILETIME is in units of 100 nsec. */
784 /* XXX Win32 supports time stamps past 2038; we currently don't */
785 *time_out
= Py_SAFE_DOWNCAST((in
/ 10000000) - secs_between_epochs
, __int64
, int);
789 time_t_to_FILE_TIME(int time_in
, int nsec_in
, FILETIME
*out_ptr
)
793 out
= time_in
+ secs_between_epochs
;
794 out
= out
* 10000000 + nsec_in
/ 100;
795 memcpy(out_ptr
, &out
, sizeof(out
));
798 /* Below, we *know* that ugo+r is 0444 */
800 #error Unsupported C library
803 attributes_to_mode(DWORD attr
)
806 if (attr
& FILE_ATTRIBUTE_DIRECTORY
)
807 m
|= _S_IFDIR
| 0111; /* IFEXEC for user,group,other */
810 if (attr
& FILE_ATTRIBUTE_READONLY
)
818 attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA
*info
, struct win32_stat
*result
)
820 memset(result
, 0, sizeof(*result
));
821 result
->st_mode
= attributes_to_mode(info
->dwFileAttributes
);
822 result
->st_size
= (((__int64
)info
->nFileSizeHigh
)<<32) + info
->nFileSizeLow
;
823 FILE_TIME_to_time_t_nsec(&info
->ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
824 FILE_TIME_to_time_t_nsec(&info
->ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
825 FILE_TIME_to_time_t_nsec(&info
->ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
830 /* Emulate GetFileAttributesEx[AW] on Windows 95 */
831 static int checked
= 0;
832 static BOOL (CALLBACK
*gfaxa
)(LPCSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
833 static BOOL (CALLBACK
*gfaxw
)(LPCWSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
841 hKernel32
= GetModuleHandle("KERNEL32");
842 *(FARPROC
*)&gfaxa
= GetProcAddress(hKernel32
, "GetFileAttributesExA");
843 *(FARPROC
*)&gfaxw
= GetProcAddress(hKernel32
, "GetFileAttributesExW");
847 attributes_from_dir(LPCSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
850 WIN32_FIND_DATAA FileData
;
851 hFindFile
= FindFirstFileA(pszFile
, &FileData
);
852 if (hFindFile
== INVALID_HANDLE_VALUE
)
854 FindClose(hFindFile
);
855 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
856 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
857 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
858 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
859 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
860 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
865 attributes_from_dir_w(LPCWSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
868 WIN32_FIND_DATAW FileData
;
869 hFindFile
= FindFirstFileW(pszFile
, &FileData
);
870 if (hFindFile
== INVALID_HANDLE_VALUE
)
872 FindClose(hFindFile
);
873 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
874 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
875 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
876 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
877 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
878 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
883 Py_GetFileAttributesExA(LPCSTR pszFile
,
884 GET_FILEEX_INFO_LEVELS level
,
888 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
889 /* First try to use the system's implementation, if that is
890 available and either succeeds to gives an error other than
891 that it isn't implemented. */
894 result
= gfaxa(pszFile
, level
, pv
);
895 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
898 /* It's either not present, or not implemented.
899 Emulate using FindFirstFile. */
900 if (level
!= GetFileExInfoStandard
) {
901 SetLastError(ERROR_INVALID_PARAMETER
);
904 /* Use GetFileAttributes to validate that the file name
905 does not contain wildcards (which FindFirstFile would
907 if (GetFileAttributesA(pszFile
) == 0xFFFFFFFF)
909 return attributes_from_dir(pszFile
, pfad
);
913 Py_GetFileAttributesExW(LPCWSTR pszFile
,
914 GET_FILEEX_INFO_LEVELS level
,
918 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
919 /* First try to use the system's implementation, if that is
920 available and either succeeds to gives an error other than
921 that it isn't implemented. */
924 result
= gfaxw(pszFile
, level
, pv
);
925 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
928 /* It's either not present, or not implemented.
929 Emulate using FindFirstFile. */
930 if (level
!= GetFileExInfoStandard
) {
931 SetLastError(ERROR_INVALID_PARAMETER
);
934 /* Use GetFileAttributes to validate that the file name
935 does not contain wildcards (which FindFirstFile would
937 if (GetFileAttributesW(pszFile
) == 0xFFFFFFFF)
939 return attributes_from_dir_w(pszFile
, pfad
);
943 win32_stat(const char* path
, struct win32_stat
*result
)
945 WIN32_FILE_ATTRIBUTE_DATA info
;
948 /* XXX not supported on Win95 and NT 3.x */
949 if (!Py_GetFileAttributesExA(path
, GetFileExInfoStandard
, &info
)) {
950 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
951 /* Protocol violation: we explicitly clear errno, instead of
952 setting it to a POSIX error. Callers should use GetLastError. */
956 /* Could not get attributes on open file. Fall back to
957 reading the directory. */
958 if (!attributes_from_dir(path
, &info
)) {
959 /* Very strange. This should not fail now */
965 code
= attribute_data_to_stat(&info
, result
);
968 /* Set S_IFEXEC if it is an .exe, .bat, ... */
969 dot
= strrchr(path
, '.');
971 if (stricmp(dot
, ".bat") == 0 ||
972 stricmp(dot
, ".cmd") == 0 ||
973 stricmp(dot
, ".exe") == 0 ||
974 stricmp(dot
, ".com") == 0)
975 result
->st_mode
|= 0111;
981 win32_wstat(const wchar_t* path
, struct win32_stat
*result
)
985 WIN32_FILE_ATTRIBUTE_DATA info
;
986 /* XXX not supported on Win95 and NT 3.x */
987 if (!Py_GetFileAttributesExW(path
, GetFileExInfoStandard
, &info
)) {
988 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
989 /* Protocol violation: we explicitly clear errno, instead of
990 setting it to a POSIX error. Callers should use GetLastError. */
994 /* Could not get attributes on open file. Fall back to
995 reading the directory. */
996 if (!attributes_from_dir_w(path
, &info
)) {
997 /* Very strange. This should not fail now */
1003 code
= attribute_data_to_stat(&info
, result
);
1006 /* Set IFEXEC if it is an .exe, .bat, ... */
1007 dot
= wcsrchr(path
, '.');
1009 if (_wcsicmp(dot
, L
".bat") == 0 ||
1010 _wcsicmp(dot
, L
".cmd") == 0 ||
1011 _wcsicmp(dot
, L
".exe") == 0 ||
1012 _wcsicmp(dot
, L
".com") == 0)
1013 result
->st_mode
|= 0111;
1019 win32_fstat(int file_number
, struct win32_stat
*result
)
1021 BY_HANDLE_FILE_INFORMATION info
;
1025 h
= (HANDLE
)_get_osfhandle(file_number
);
1027 /* Protocol violation: we explicitly clear errno, instead of
1028 setting it to a POSIX error. Callers should use GetLastError. */
1031 if (h
== INVALID_HANDLE_VALUE
) {
1032 /* This is really a C library error (invalid file handle).
1033 We set the Win32 error to the closes one matching. */
1034 SetLastError(ERROR_INVALID_HANDLE
);
1037 memset(result
, 0, sizeof(*result
));
1039 type
= GetFileType(h
);
1040 if (type
== FILE_TYPE_UNKNOWN
) {
1041 DWORD error
= GetLastError();
1045 /* else: valid but unknown file */
1048 if (type
!= FILE_TYPE_DISK
) {
1049 if (type
== FILE_TYPE_CHAR
)
1050 result
->st_mode
= _S_IFCHR
;
1051 else if (type
== FILE_TYPE_PIPE
)
1052 result
->st_mode
= _S_IFIFO
;
1056 if (!GetFileInformationByHandle(h
, &info
)) {
1060 /* similar to stat() */
1061 result
->st_mode
= attributes_to_mode(info
.dwFileAttributes
);
1062 result
->st_size
= (((__int64
)info
.nFileSizeHigh
)<<32) + info
.nFileSizeLow
;
1063 FILE_TIME_to_time_t_nsec(&info
.ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
1064 FILE_TIME_to_time_t_nsec(&info
.ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
1065 FILE_TIME_to_time_t_nsec(&info
.ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
1066 /* specific to fstat() */
1067 result
->st_nlink
= info
.nNumberOfLinks
;
1068 result
->st_ino
= (((__int64
)info
.nFileIndexHigh
)<<32) + info
.nFileIndexLow
;
1072 #endif /* MS_WINDOWS */
1074 PyDoc_STRVAR(stat_result__doc__
,
1075 "stat_result: Result from stat or lstat.\n\n\
1076 This object may be accessed either as a tuple of\n\
1077 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
1078 or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1080 Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1081 or st_flags, they are available as attributes only.\n\
1083 See os.stat for more information.");
1085 static PyStructSequence_Field stat_result_fields
[] = {
1086 {"st_mode", "protection bits"},
1087 {"st_ino", "inode"},
1088 {"st_dev", "device"},
1089 {"st_nlink", "number of hard links"},
1090 {"st_uid", "user ID of owner"},
1091 {"st_gid", "group ID of owner"},
1092 {"st_size", "total size, in bytes"},
1093 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1094 {NULL
, "integer time of last access"},
1095 {NULL
, "integer time of last modification"},
1096 {NULL
, "integer time of last change"},
1097 {"st_atime", "time of last access"},
1098 {"st_mtime", "time of last modification"},
1099 {"st_ctime", "time of last change"},
1100 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1101 {"st_blksize", "blocksize for filesystem I/O"},
1103 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1104 {"st_blocks", "number of blocks allocated"},
1106 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1107 {"st_rdev", "device type (if inode device)"},
1109 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1110 {"st_flags", "user defined flags for file"},
1112 #ifdef HAVE_STRUCT_STAT_ST_GEN
1113 {"st_gen", "generation number"},
1115 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1116 {"st_birthtime", "time of creation"},
1121 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1122 #define ST_BLKSIZE_IDX 13
1124 #define ST_BLKSIZE_IDX 12
1127 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1128 #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1130 #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1133 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1134 #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1136 #define ST_RDEV_IDX ST_BLOCKS_IDX
1139 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1140 #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1142 #define ST_FLAGS_IDX ST_RDEV_IDX
1145 #ifdef HAVE_STRUCT_STAT_ST_GEN
1146 #define ST_GEN_IDX (ST_FLAGS_IDX+1)
1148 #define ST_GEN_IDX ST_FLAGS_IDX
1151 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1152 #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1154 #define ST_BIRTHTIME_IDX ST_GEN_IDX
1157 static PyStructSequence_Desc stat_result_desc
= {
1158 "stat_result", /* name */
1159 stat_result__doc__
, /* doc */
1164 PyDoc_STRVAR(statvfs_result__doc__
,
1165 "statvfs_result: Result from statvfs or fstatvfs.\n\n\
1166 This object may be accessed either as a tuple of\n\
1167 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
1168 or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
1170 See os.statvfs for more information.");
1172 static PyStructSequence_Field statvfs_result_fields
[] = {
1186 static PyStructSequence_Desc statvfs_result_desc
= {
1187 "statvfs_result", /* name */
1188 statvfs_result__doc__
, /* doc */
1189 statvfs_result_fields
,
1193 static int initialized
;
1194 static PyTypeObject StatResultType
;
1195 static PyTypeObject StatVFSResultType
;
1196 static newfunc structseq_new
;
1199 statresult_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1201 PyStructSequence
*result
;
1204 result
= (PyStructSequence
*)structseq_new(type
, args
, kwds
);
1207 /* If we have been initialized from a tuple,
1208 st_?time might be set to None. Initialize it
1209 from the int slots. */
1210 for (i
= 7; i
<= 9; i
++) {
1211 if (result
->ob_item
[i
+3] == Py_None
) {
1213 Py_INCREF(result
->ob_item
[i
]);
1214 result
->ob_item
[i
+3] = result
->ob_item
[i
];
1217 return (PyObject
*)result
;
1222 /* If true, st_?time is float. */
1223 static int _stat_float_times
= 1;
1225 PyDoc_STRVAR(stat_float_times__doc__
,
1226 "stat_float_times([newval]) -> oldval\n\n\
1227 Determine whether os.[lf]stat represents time stamps as float objects.\n\
1228 If newval is True, future calls to stat() return floats, if it is False,\n\
1229 future calls return ints. \n\
1230 If newval is omitted, return the current setting.\n");
1233 stat_float_times(PyObject
* self
, PyObject
*args
)
1236 if (!PyArg_ParseTuple(args
, "|i:stat_float_times", &newval
))
1239 /* Return old value */
1240 return PyBool_FromLong(_stat_float_times
);
1241 _stat_float_times
= newval
;
1247 fill_time(PyObject
*v
, int index
, time_t sec
, unsigned long nsec
)
1249 PyObject
*fval
,*ival
;
1250 #if SIZEOF_TIME_T > SIZEOF_LONG
1251 ival
= PyLong_FromLongLong((PY_LONG_LONG
)sec
);
1253 ival
= PyInt_FromLong((long)sec
);
1257 if (_stat_float_times
) {
1258 fval
= PyFloat_FromDouble(sec
+ 1e-9*nsec
);
1263 PyStructSequence_SET_ITEM(v
, index
, ival
);
1264 PyStructSequence_SET_ITEM(v
, index
+3, fval
);
1267 /* pack a system stat C structure into the Python stat tuple
1268 (used by posix_stat() and posix_fstat()) */
1270 _pystat_fromstructstat(STRUCT_STAT
*st
)
1272 unsigned long ansec
, mnsec
, cnsec
;
1273 PyObject
*v
= PyStructSequence_New(&StatResultType
);
1277 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long)st
->st_mode
));
1278 #ifdef HAVE_LARGEFILE_SUPPORT
1279 PyStructSequence_SET_ITEM(v
, 1,
1280 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_ino
));
1282 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long)st
->st_ino
));
1284 #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
1285 PyStructSequence_SET_ITEM(v
, 2,
1286 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_dev
));
1288 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long)st
->st_dev
));
1290 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long)st
->st_nlink
));
1291 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long)st
->st_uid
));
1292 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long)st
->st_gid
));
1293 #ifdef HAVE_LARGEFILE_SUPPORT
1294 PyStructSequence_SET_ITEM(v
, 6,
1295 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_size
));
1297 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong(st
->st_size
));
1300 #if defined(HAVE_STAT_TV_NSEC)
1301 ansec
= st
->st_atim
.tv_nsec
;
1302 mnsec
= st
->st_mtim
.tv_nsec
;
1303 cnsec
= st
->st_ctim
.tv_nsec
;
1304 #elif defined(HAVE_STAT_TV_NSEC2)
1305 ansec
= st
->st_atimespec
.tv_nsec
;
1306 mnsec
= st
->st_mtimespec
.tv_nsec
;
1307 cnsec
= st
->st_ctimespec
.tv_nsec
;
1308 #elif defined(HAVE_STAT_NSEC)
1309 ansec
= st
->st_atime_nsec
;
1310 mnsec
= st
->st_mtime_nsec
;
1311 cnsec
= st
->st_ctime_nsec
;
1313 ansec
= mnsec
= cnsec
= 0;
1315 fill_time(v
, 7, st
->st_atime
, ansec
);
1316 fill_time(v
, 8, st
->st_mtime
, mnsec
);
1317 fill_time(v
, 9, st
->st_ctime
, cnsec
);
1319 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1320 PyStructSequence_SET_ITEM(v
, ST_BLKSIZE_IDX
,
1321 PyInt_FromLong((long)st
->st_blksize
));
1323 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1324 PyStructSequence_SET_ITEM(v
, ST_BLOCKS_IDX
,
1325 PyInt_FromLong((long)st
->st_blocks
));
1327 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1328 PyStructSequence_SET_ITEM(v
, ST_RDEV_IDX
,
1329 PyInt_FromLong((long)st
->st_rdev
));
1331 #ifdef HAVE_STRUCT_STAT_ST_GEN
1332 PyStructSequence_SET_ITEM(v
, ST_GEN_IDX
,
1333 PyInt_FromLong((long)st
->st_gen
));
1335 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1338 unsigned long bsec
,bnsec
;
1339 bsec
= (long)st
->st_birthtime
;
1340 #ifdef HAVE_STAT_TV_NSEC2
1341 bnsec
= st
->st_birthtimespec
.tv_nsec
;
1345 if (_stat_float_times
) {
1346 val
= PyFloat_FromDouble(bsec
+ 1e-9*bnsec
);
1348 val
= PyInt_FromLong((long)bsec
);
1350 PyStructSequence_SET_ITEM(v
, ST_BIRTHTIME_IDX
,
1354 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1355 PyStructSequence_SET_ITEM(v
, ST_FLAGS_IDX
,
1356 PyInt_FromLong((long)st
->st_flags
));
1359 if (PyErr_Occurred()) {
1369 /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
1370 where / can be used in place of \ and the trailing slash is optional.
1371 Both SERVER and SHARE must have at least one character.
1374 #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
1375 #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
1377 #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
1381 IsUNCRootA(char *path
, int pathlen
)
1383 #define ISSLASH ISSLASHA
1387 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1388 /* minimum UNCRoot is \\x\y */
1390 for (i
= 2; i
< pathlen
; i
++)
1391 if (ISSLASH(path
[i
])) break;
1392 if (i
== 2 || i
== pathlen
)
1393 /* do not allow \\\SHARE or \\SERVER */
1396 for (i
= share
; i
< pathlen
; i
++)
1397 if (ISSLASH(path
[i
])) break;
1398 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1403 #ifdef Py_WIN_WIDE_FILENAMES
1405 IsUNCRootW(Py_UNICODE
*path
, int pathlen
)
1407 #define ISSLASH ISSLASHW
1411 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1412 /* minimum UNCRoot is \\x\y */
1414 for (i
= 2; i
< pathlen
; i
++)
1415 if (ISSLASH(path
[i
])) break;
1416 if (i
== 2 || i
== pathlen
)
1417 /* do not allow \\\SHARE or \\SERVER */
1420 for (i
= share
; i
< pathlen
; i
++)
1421 if (ISSLASH(path
[i
])) break;
1422 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1426 #endif /* Py_WIN_WIDE_FILENAMES */
1427 #endif /* MS_WINDOWS */
1430 posix_do_stat(PyObject
*self
, PyObject
*args
,
1433 int (*statfunc
)(const char *, STRUCT_STAT
*, ...),
1435 int (*statfunc
)(const char *, STRUCT_STAT
*),
1438 int (*wstatfunc
)(const Py_UNICODE
*, STRUCT_STAT
*))
1441 char *path
= NULL
; /* pass this to stat; do not free() it */
1442 char *pathfree
= NULL
; /* this memory must be free'd */
1446 #ifdef Py_WIN_WIDE_FILENAMES
1447 /* If on wide-character-capable OS see if argument
1448 is Unicode and if so use wide API. */
1449 if (unicode_file_names()) {
1450 PyUnicodeObject
*po
;
1451 if (PyArg_ParseTuple(args
, wformat
, &po
)) {
1452 Py_UNICODE
*wpath
= PyUnicode_AS_UNICODE(po
);
1454 Py_BEGIN_ALLOW_THREADS
1455 /* PyUnicode_AS_UNICODE result OK without
1456 thread lock as it is a simple dereference. */
1457 res
= wstatfunc(wpath
, &st
);
1458 Py_END_ALLOW_THREADS
1461 return win32_error_unicode("stat", wpath
);
1462 return _pystat_fromstructstat(&st
);
1464 /* Drop the argument parsing error as narrow strings
1470 if (!PyArg_ParseTuple(args
, format
,
1471 Py_FileSystemDefaultEncoding
, &path
))
1475 Py_BEGIN_ALLOW_THREADS
1476 res
= (*statfunc
)(path
, &st
);
1477 Py_END_ALLOW_THREADS
1481 result
= win32_error("stat", pathfree
);
1483 result
= posix_error_with_filename(pathfree
);
1487 result
= _pystat_fromstructstat(&st
);
1489 PyMem_Free(pathfree
);
1495 PyDoc_STRVAR(posix_access__doc__
,
1496 "access(path, mode) -> True if granted, False otherwise\n\n\
1497 Use the real uid/gid to test for access to a path. Note that most\n\
1498 operations will use the effective uid/gid, therefore this routine can\n\
1499 be used in a suid/sgid environment to test if the invoking user has the\n\
1500 specified access to the path. The mode argument can be F_OK to test\n\
1501 existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
1504 posix_access(PyObject
*self
, PyObject
*args
)
1509 #ifdef Py_WIN_WIDE_FILENAMES
1511 if (unicode_file_names()) {
1512 PyUnicodeObject
*po
;
1513 if (PyArg_ParseTuple(args
, "Ui:access", &po
, &mode
)) {
1514 Py_BEGIN_ALLOW_THREADS
1515 /* PyUnicode_AS_UNICODE OK without thread lock as
1516 it is a simple dereference. */
1517 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1518 Py_END_ALLOW_THREADS
1521 /* Drop the argument parsing error as narrow strings
1525 if (!PyArg_ParseTuple(args
, "eti:access",
1526 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1528 Py_BEGIN_ALLOW_THREADS
1529 attr
= GetFileAttributesA(path
);
1530 Py_END_ALLOW_THREADS
1533 if (attr
== 0xFFFFFFFF)
1534 /* File does not exist, or cannot read attributes */
1535 return PyBool_FromLong(0);
1536 /* Access is possible if either write access wasn't requested, or
1537 the file isn't read-only. */
1538 return PyBool_FromLong(!(mode
& 2) || !(attr
& FILE_ATTRIBUTE_READONLY
));
1541 if (!PyArg_ParseTuple(args
, "eti:access",
1542 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1544 Py_BEGIN_ALLOW_THREADS
1545 res
= access(path
, mode
);
1546 Py_END_ALLOW_THREADS
1548 return PyBool_FromLong(res
== 0);
1566 PyDoc_STRVAR(posix_ttyname__doc__
,
1567 "ttyname(fd) -> string\n\n\
1568 Return the name of the terminal device connected to 'fd'.");
1571 posix_ttyname(PyObject
*self
, PyObject
*args
)
1576 if (!PyArg_ParseTuple(args
, "i:ttyname", &id
))
1580 /* file descriptor 0 only, the default input device (stdin) */
1591 return posix_error();
1592 return PyString_FromString(ret
);
1597 PyDoc_STRVAR(posix_ctermid__doc__
,
1598 "ctermid() -> string\n\n\
1599 Return the name of the controlling terminal for this process.");
1602 posix_ctermid(PyObject
*self
, PyObject
*noargs
)
1605 char buffer
[L_ctermid
];
1607 #ifdef USE_CTERMID_R
1608 ret
= ctermid_r(buffer
);
1610 ret
= ctermid(buffer
);
1613 return posix_error();
1614 return PyString_FromString(buffer
);
1618 PyDoc_STRVAR(posix_chdir__doc__
,
1620 Change the current working directory to the specified path.");
1623 posix_chdir(PyObject
*self
, PyObject
*args
)
1626 return win32_1str(args
, "chdir", "s:chdir", win32_chdir
, "U:chdir", win32_wchdir
);
1627 #elif defined(PYOS_OS2) && defined(PYCC_GCC)
1628 return posix_1str(args
, "et:chdir", _chdir2
);
1629 #elif defined(__VMS)
1630 return posix_1str(args
, "et:chdir", (int (*)(const char *))chdir
);
1632 return posix_1str(args
, "et:chdir", chdir
);
1637 PyDoc_STRVAR(posix_fchdir__doc__
,
1638 "fchdir(fildes)\n\n\
1639 Change to the directory of the given file descriptor. fildes must be\n\
1640 opened on a directory, not a file.");
1643 posix_fchdir(PyObject
*self
, PyObject
*fdobj
)
1645 return posix_fildes(fdobj
, fchdir
);
1647 #endif /* HAVE_FCHDIR */
1650 PyDoc_STRVAR(posix_chmod__doc__
,
1651 "chmod(path, mode)\n\n\
1652 Change the access permissions of a file.");
1655 posix_chmod(PyObject
*self
, PyObject
*args
)
1660 #ifdef Py_WIN_WIDE_FILENAMES
1662 if (unicode_file_names()) {
1663 PyUnicodeObject
*po
;
1664 if (PyArg_ParseTuple(args
, "Ui|:chmod", &po
, &i
)) {
1665 Py_BEGIN_ALLOW_THREADS
1666 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1667 if (attr
!= 0xFFFFFFFF) {
1669 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1671 attr
|= FILE_ATTRIBUTE_READONLY
;
1672 res
= SetFileAttributesW(PyUnicode_AS_UNICODE(po
), attr
);
1676 Py_END_ALLOW_THREADS
1678 return win32_error_unicode("chmod",
1679 PyUnicode_AS_UNICODE(po
));
1683 /* Drop the argument parsing error as narrow strings
1687 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1690 Py_BEGIN_ALLOW_THREADS
1691 attr
= GetFileAttributesA(path
);
1692 if (attr
!= 0xFFFFFFFF) {
1694 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1696 attr
|= FILE_ATTRIBUTE_READONLY
;
1697 res
= SetFileAttributesA(path
, attr
);
1701 Py_END_ALLOW_THREADS
1703 win32_error("chmod", path
);
1710 #else /* Py_WIN_WIDE_FILENAMES */
1711 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1714 Py_BEGIN_ALLOW_THREADS
1715 res
= chmod(path
, i
);
1716 Py_END_ALLOW_THREADS
1718 return posix_error_with_allocated_filename(path
);
1727 PyDoc_STRVAR(posix_chflags__doc__
,
1728 "chflags(path, flags)\n\n\
1732 posix_chflags(PyObject
*self
, PyObject
*args
)
1735 unsigned long flags
;
1737 if (!PyArg_ParseTuple(args
, "etk:chflags",
1738 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1740 Py_BEGIN_ALLOW_THREADS
1741 res
= chflags(path
, flags
);
1742 Py_END_ALLOW_THREADS
1744 return posix_error_with_allocated_filename(path
);
1749 #endif /* HAVE_CHFLAGS */
1751 #ifdef HAVE_LCHFLAGS
1752 PyDoc_STRVAR(posix_lchflags__doc__
,
1753 "lchflags(path, flags)\n\n\
1755 This function will not follow symbolic links.");
1758 posix_lchflags(PyObject
*self
, PyObject
*args
)
1761 unsigned long flags
;
1763 if (!PyArg_ParseTuple(args
, "etk:lchflags",
1764 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1766 Py_BEGIN_ALLOW_THREADS
1767 res
= lchflags(path
, flags
);
1768 Py_END_ALLOW_THREADS
1770 return posix_error_with_allocated_filename(path
);
1775 #endif /* HAVE_LCHFLAGS */
1778 PyDoc_STRVAR(posix_chroot__doc__
,
1780 Change root directory to path.");
1783 posix_chroot(PyObject
*self
, PyObject
*args
)
1785 return posix_1str(args
, "et:chroot", chroot
);
1790 PyDoc_STRVAR(posix_fsync__doc__
,
1792 force write of file with filedescriptor to disk.");
1795 posix_fsync(PyObject
*self
, PyObject
*fdobj
)
1797 return posix_fildes(fdobj
, fsync
);
1799 #endif /* HAVE_FSYNC */
1801 #ifdef HAVE_FDATASYNC
1804 extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
1807 PyDoc_STRVAR(posix_fdatasync__doc__
,
1808 "fdatasync(fildes)\n\n\
1809 force write of file with filedescriptor to disk.\n\
1810 does not force update of metadata.");
1813 posix_fdatasync(PyObject
*self
, PyObject
*fdobj
)
1815 return posix_fildes(fdobj
, fdatasync
);
1817 #endif /* HAVE_FDATASYNC */
1821 PyDoc_STRVAR(posix_chown__doc__
,
1822 "chown(path, uid, gid)\n\n\
1823 Change the owner and group id of path to the numeric uid and gid.");
1826 posix_chown(PyObject
*self
, PyObject
*args
)
1831 if (!PyArg_ParseTuple(args
, "etii:chown",
1832 Py_FileSystemDefaultEncoding
, &path
,
1835 Py_BEGIN_ALLOW_THREADS
1836 res
= chown(path
, (uid_t
) uid
, (gid_t
) gid
);
1837 Py_END_ALLOW_THREADS
1839 return posix_error_with_allocated_filename(path
);
1844 #endif /* HAVE_CHOWN */
1847 PyDoc_STRVAR(posix_lchown__doc__
,
1848 "lchown(path, uid, gid)\n\n\
1849 Change the owner and group id of path to the numeric uid and gid.\n\
1850 This function will not follow symbolic links.");
1853 posix_lchown(PyObject
*self
, PyObject
*args
)
1858 if (!PyArg_ParseTuple(args
, "etii:lchown",
1859 Py_FileSystemDefaultEncoding
, &path
,
1862 Py_BEGIN_ALLOW_THREADS
1863 res
= lchown(path
, (uid_t
) uid
, (gid_t
) gid
);
1864 Py_END_ALLOW_THREADS
1866 return posix_error_with_allocated_filename(path
);
1871 #endif /* HAVE_LCHOWN */
1875 PyDoc_STRVAR(posix_getcwd__doc__
,
1876 "getcwd() -> path\n\n\
1877 Return a string representing the current working directory.");
1880 posix_getcwd(PyObject
*self
, PyObject
*noargs
)
1885 Py_BEGIN_ALLOW_THREADS
1886 #if defined(PYOS_OS2) && defined(PYCC_GCC)
1887 res
= _getcwd2(buf
, sizeof buf
);
1889 res
= getcwd(buf
, sizeof buf
);
1891 Py_END_ALLOW_THREADS
1893 return posix_error();
1894 return PyString_FromString(buf
);
1897 #ifdef Py_USING_UNICODE
1898 PyDoc_STRVAR(posix_getcwdu__doc__
,
1899 "getcwdu() -> path\n\n\
1900 Return a unicode string representing the current working directory.");
1903 posix_getcwdu(PyObject
*self
, PyObject
*noargs
)
1908 #ifdef Py_WIN_WIDE_FILENAMES
1910 if (unicode_file_names()) {
1912 wchar_t *wbuf2
= wbuf
;
1914 Py_BEGIN_ALLOW_THREADS
1915 len
= GetCurrentDirectoryW(sizeof wbuf
/ sizeof wbuf
[0], wbuf
);
1916 /* If the buffer is large enough, len does not include the
1917 terminating \0. If the buffer is too small, len includes
1918 the space needed for the terminator. */
1919 if (len
>= sizeof wbuf
/ sizeof wbuf
[0]) {
1920 wbuf2
= malloc(len
* sizeof(wchar_t));
1922 len
= GetCurrentDirectoryW(len
, wbuf2
);
1924 Py_END_ALLOW_THREADS
1930 if (wbuf2
!= wbuf
) free(wbuf2
);
1931 return win32_error("getcwdu", NULL
);
1933 resobj
= PyUnicode_FromWideChar(wbuf2
, len
);
1934 if (wbuf2
!= wbuf
) free(wbuf2
);
1939 Py_BEGIN_ALLOW_THREADS
1940 #if defined(PYOS_OS2) && defined(PYCC_GCC)
1941 res
= _getcwd2(buf
, sizeof buf
);
1943 res
= getcwd(buf
, sizeof buf
);
1945 Py_END_ALLOW_THREADS
1947 return posix_error();
1948 return PyUnicode_Decode(buf
, strlen(buf
), Py_FileSystemDefaultEncoding
,"strict");
1955 PyDoc_STRVAR(posix_link__doc__
,
1956 "link(src, dst)\n\n\
1957 Create a hard link to a file.");
1960 posix_link(PyObject
*self
, PyObject
*args
)
1962 return posix_2str(args
, "etet:link", link
);
1964 #endif /* HAVE_LINK */
1967 PyDoc_STRVAR(posix_listdir__doc__
,
1968 "listdir(path) -> list_of_strings\n\n\
1969 Return a list containing the names of the entries in the directory.\n\
1971 path: path of directory to list\n\
1973 The list is in arbitrary order. It does not include the special\n\
1974 entries '.' and '..' even if they are present in the directory.");
1977 posix_listdir(PyObject
*self
, PyObject
*args
)
1979 /* XXX Should redo this putting the (now four) versions of opendir
1980 in separate files instead of having them all here... */
1981 #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
1986 WIN32_FIND_DATA FileData
;
1987 char namebuf
[MAX_PATH
+5]; /* Overallocate for \\*.*\0 */
1988 char *bufptr
= namebuf
;
1989 Py_ssize_t len
= sizeof(namebuf
)-5; /* only claim to have space for MAX_PATH */
1991 #ifdef Py_WIN_WIDE_FILENAMES
1992 /* If on wide-character-capable OS see if argument
1993 is Unicode and if so use wide API. */
1994 if (unicode_file_names()) {
1996 if (PyArg_ParseTuple(args
, "U:listdir", &po
)) {
1997 WIN32_FIND_DATAW wFileData
;
1998 Py_UNICODE
*wnamebuf
;
2000 /* Overallocate for \\*.*\0 */
2001 len
= PyUnicode_GET_SIZE(po
);
2002 wnamebuf
= malloc((len
+ 5) * sizeof(wchar_t));
2007 wcscpy(wnamebuf
, PyUnicode_AS_UNICODE(po
));
2008 wch
= len
> 0 ? wnamebuf
[len
-1] : '\0';
2009 if (wch
!= L
'/' && wch
!= L
'\\' && wch
!= L
':')
2010 wnamebuf
[len
++] = L
'\\';
2011 wcscpy(wnamebuf
+ len
, L
"*.*");
2012 if ((d
= PyList_New(0)) == NULL
) {
2016 hFindFile
= FindFirstFileW(wnamebuf
, &wFileData
);
2017 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2018 int error
= GetLastError();
2019 if (error
== ERROR_FILE_NOT_FOUND
) {
2024 win32_error_unicode("FindFirstFileW", wnamebuf
);
2029 /* Skip over . and .. */
2030 if (wcscmp(wFileData
.cFileName
, L
".") != 0 &&
2031 wcscmp(wFileData
.cFileName
, L
"..") != 0) {
2032 v
= PyUnicode_FromUnicode(wFileData
.cFileName
, wcslen(wFileData
.cFileName
));
2038 if (PyList_Append(d
, v
) != 0) {
2046 Py_BEGIN_ALLOW_THREADS
2047 result
= FindNextFileW(hFindFile
, &wFileData
);
2048 Py_END_ALLOW_THREADS
2049 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2050 it got to the end of the directory. */
2051 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2053 win32_error_unicode("FindNextFileW", wnamebuf
);
2054 FindClose(hFindFile
);
2058 } while (result
== TRUE
);
2060 if (FindClose(hFindFile
) == FALSE
) {
2062 win32_error_unicode("FindClose", wnamebuf
);
2069 /* Drop the argument parsing error as narrow strings
2075 if (!PyArg_ParseTuple(args
, "et#:listdir",
2076 Py_FileSystemDefaultEncoding
, &bufptr
, &len
))
2079 char ch
= namebuf
[len
-1];
2080 if (ch
!= SEP
&& ch
!= ALTSEP
&& ch
!= ':')
2081 namebuf
[len
++] = '/';
2083 strcpy(namebuf
+ len
, "*.*");
2085 if ((d
= PyList_New(0)) == NULL
)
2088 hFindFile
= FindFirstFile(namebuf
, &FileData
);
2089 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2090 int error
= GetLastError();
2091 if (error
== ERROR_FILE_NOT_FOUND
)
2094 return win32_error("FindFirstFile", namebuf
);
2097 /* Skip over . and .. */
2098 if (strcmp(FileData
.cFileName
, ".") != 0 &&
2099 strcmp(FileData
.cFileName
, "..") != 0) {
2100 v
= PyString_FromString(FileData
.cFileName
);
2106 if (PyList_Append(d
, v
) != 0) {
2114 Py_BEGIN_ALLOW_THREADS
2115 result
= FindNextFile(hFindFile
, &FileData
);
2116 Py_END_ALLOW_THREADS
2117 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2118 it got to the end of the directory. */
2119 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2121 win32_error("FindNextFile", namebuf
);
2122 FindClose(hFindFile
);
2125 } while (result
== TRUE
);
2127 if (FindClose(hFindFile
) == FALSE
) {
2129 return win32_error("FindClose", namebuf
);
2134 #elif defined(PYOS_OS2)
2137 #define MAX_PATH CCHMAXPATH
2142 char namebuf
[MAX_PATH
+5];
2148 if (!PyArg_ParseTuple(args
, "t#:listdir", &name
, &len
))
2150 if (len
>= MAX_PATH
) {
2151 PyErr_SetString(PyExc_ValueError
, "path too long");
2154 strcpy(namebuf
, name
);
2155 for (pt
= namebuf
; *pt
; pt
++)
2158 if (namebuf
[len
-1] != SEP
)
2159 namebuf
[len
++] = SEP
;
2160 strcpy(namebuf
+ len
, "*.*");
2162 if ((d
= PyList_New(0)) == NULL
)
2165 rc
= DosFindFirst(namebuf
, /* Wildcard Pattern to Match */
2166 &hdir
, /* Handle to Use While Search Directory */
2167 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
2168 &ep
, sizeof(ep
), /* Structure to Receive Directory Entry */
2169 &srchcnt
, /* Max and Actual Count of Entries Per Iteration */
2170 FIL_STANDARD
); /* Format of Entry (EAs or Not) */
2172 if (rc
!= NO_ERROR
) {
2174 return posix_error_with_filename(name
);
2177 if (srchcnt
> 0) { /* If Directory is NOT Totally Empty, */
2179 if (ep
.achName
[0] == '.'
2180 && (ep
.achName
[1] == '\0' || (ep
.achName
[1] == '.' && ep
.achName
[2] == '\0')))
2181 continue; /* Skip Over "." and ".." Names */
2183 strcpy(namebuf
, ep
.achName
);
2185 /* Leave Case of Name Alone -- In Native Form */
2186 /* (Removed Forced Lowercasing Code) */
2188 v
= PyString_FromString(namebuf
);
2194 if (PyList_Append(d
, v
) != 0) {
2201 } while (DosFindNext(hdir
, &ep
, sizeof(ep
), &srchcnt
) == NO_ERROR
&& srchcnt
> 0);
2211 int arg_is_unicode
= 1;
2214 if (!PyArg_ParseTuple(args
, "U:listdir", &v
)) {
2218 if (!PyArg_ParseTuple(args
, "et:listdir", Py_FileSystemDefaultEncoding
, &name
))
2220 if ((dirp
= opendir(name
)) == NULL
) {
2221 return posix_error_with_allocated_filename(name
);
2223 if ((d
= PyList_New(0)) == NULL
) {
2229 Py_BEGIN_ALLOW_THREADS
2231 Py_END_ALLOW_THREADS
2234 if (ep
->d_name
[0] == '.' &&
2236 (ep
->d_name
[1] == '.' && NAMLEN(ep
) == 2)))
2238 v
= PyString_FromStringAndSize(ep
->d_name
, NAMLEN(ep
));
2244 #ifdef Py_USING_UNICODE
2245 if (arg_is_unicode
) {
2248 w
= PyUnicode_FromEncodedObject(v
,
2249 Py_FileSystemDefaultEncoding
,
2256 /* fall back to the original byte string, as
2257 discussed in patch #683592 */
2262 if (PyList_Append(d
, v
) != 0) {
2270 if (errno
!= 0 && d
!= NULL
) {
2271 /* readdir() returned NULL and set errno */
2274 return posix_error_with_allocated_filename(name
);
2281 #endif /* which OS */
2282 } /* end of posix_listdir */
2285 /* A helper function for abspath on win32 */
2287 posix__getfullpathname(PyObject
*self
, PyObject
*args
)
2289 /* assume encoded strings wont more than double no of chars */
2290 char inbuf
[MAX_PATH
*2];
2291 char *inbufp
= inbuf
;
2292 Py_ssize_t insize
= sizeof(inbuf
);
2293 char outbuf
[MAX_PATH
*2];
2295 #ifdef Py_WIN_WIDE_FILENAMES
2296 if (unicode_file_names()) {
2297 PyUnicodeObject
*po
;
2298 if (PyArg_ParseTuple(args
, "U|:_getfullpathname", &po
)) {
2299 Py_UNICODE woutbuf
[MAX_PATH
*2];
2301 if (!GetFullPathNameW(PyUnicode_AS_UNICODE(po
),
2302 sizeof(woutbuf
)/sizeof(woutbuf
[0]),
2304 return win32_error("GetFullPathName", "");
2305 return PyUnicode_FromUnicode(woutbuf
, wcslen(woutbuf
));
2307 /* Drop the argument parsing error as narrow strings
2312 if (!PyArg_ParseTuple (args
, "et#:_getfullpathname",
2313 Py_FileSystemDefaultEncoding
, &inbufp
,
2316 if (!GetFullPathName(inbuf
, sizeof(outbuf
)/sizeof(outbuf
[0]),
2318 return win32_error("GetFullPathName", inbuf
);
2319 if (PyUnicode_Check(PyTuple_GetItem(args
, 0))) {
2320 return PyUnicode_Decode(outbuf
, strlen(outbuf
),
2321 Py_FileSystemDefaultEncoding
, NULL
);
2323 return PyString_FromString(outbuf
);
2324 } /* end of posix__getfullpathname */
2325 #endif /* MS_WINDOWS */
2327 PyDoc_STRVAR(posix_mkdir__doc__
,
2328 "mkdir(path [, mode=0777])\n\n\
2329 Create a directory.");
2332 posix_mkdir(PyObject
*self
, PyObject
*args
)
2338 #ifdef Py_WIN_WIDE_FILENAMES
2339 if (unicode_file_names()) {
2340 PyUnicodeObject
*po
;
2341 if (PyArg_ParseTuple(args
, "U|i:mkdir", &po
, &mode
)) {
2342 Py_BEGIN_ALLOW_THREADS
2343 /* PyUnicode_AS_UNICODE OK without thread lock as
2344 it is a simple dereference. */
2345 res
= CreateDirectoryW(PyUnicode_AS_UNICODE(po
), NULL
);
2346 Py_END_ALLOW_THREADS
2348 return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po
));
2352 /* Drop the argument parsing error as narrow strings
2356 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2357 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2359 Py_BEGIN_ALLOW_THREADS
2360 /* PyUnicode_AS_UNICODE OK without thread lock as
2361 it is a simple dereference. */
2362 res
= CreateDirectoryA(path
, NULL
);
2363 Py_END_ALLOW_THREADS
2365 win32_error("mkdir", path
);
2374 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2375 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2377 Py_BEGIN_ALLOW_THREADS
2378 #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
2381 res
= mkdir(path
, mode
);
2383 Py_END_ALLOW_THREADS
2385 return posix_error_with_allocated_filename(path
);
2393 /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
2394 #if defined(HAVE_SYS_RESOURCE_H)
2395 #include <sys/resource.h>
2400 PyDoc_STRVAR(posix_nice__doc__
,
2401 "nice(inc) -> new_priority\n\n\
2402 Decrease the priority of process by inc and return the new priority.");
2405 posix_nice(PyObject
*self
, PyObject
*args
)
2407 int increment
, value
;
2409 if (!PyArg_ParseTuple(args
, "i:nice", &increment
))
2412 /* There are two flavours of 'nice': one that returns the new
2413 priority (as required by almost all standards out there) and the
2414 Linux/FreeBSD/BSDI one, which returns '0' on success and advices
2415 the use of getpriority() to get the new priority.
2417 If we are of the nice family that returns the new priority, we
2418 need to clear errno before the call, and check if errno is filled
2419 before calling posix_error() on a returnvalue of -1, because the
2420 -1 may be the actual new priority! */
2423 value
= nice(increment
);
2424 #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
2426 value
= getpriority(PRIO_PROCESS
, 0);
2428 if (value
== -1 && errno
!= 0)
2429 /* either nice() or getpriority() returned an error */
2430 return posix_error();
2431 return PyInt_FromLong((long) value
);
2433 #endif /* HAVE_NICE */
2435 PyDoc_STRVAR(posix_rename__doc__
,
2436 "rename(old, new)\n\n\
2437 Rename a file or directory.");
2440 posix_rename(PyObject
*self
, PyObject
*args
)
2446 if (unicode_file_names()) {
2447 if (!PyArg_ParseTuple(args
, "O&O&:rename",
2448 convert_to_unicode
, &o1
,
2449 convert_to_unicode
, &o2
))
2452 Py_BEGIN_ALLOW_THREADS
2453 result
= MoveFileW(PyUnicode_AsUnicode(o1
),
2454 PyUnicode_AsUnicode(o2
));
2455 Py_END_ALLOW_THREADS
2459 return win32_error("rename", NULL
);
2464 if (!PyArg_ParseTuple(args
, "ss:rename", &p1
, &p2
))
2466 Py_BEGIN_ALLOW_THREADS
2467 result
= MoveFileA(p1
, p2
);
2468 Py_END_ALLOW_THREADS
2470 return win32_error("rename", NULL
);
2474 return posix_2str(args
, "etet:rename", rename
);
2479 PyDoc_STRVAR(posix_rmdir__doc__
,
2481 Remove a directory.");
2484 posix_rmdir(PyObject
*self
, PyObject
*args
)
2487 return win32_1str(args
, "rmdir", "s:rmdir", RemoveDirectoryA
, "U:rmdir", RemoveDirectoryW
);
2489 return posix_1str(args
, "et:rmdir", rmdir
);
2494 PyDoc_STRVAR(posix_stat__doc__
,
2495 "stat(path) -> stat result\n\n\
2496 Perform a stat system call on the given path.");
2499 posix_stat(PyObject
*self
, PyObject
*args
)
2502 return posix_do_stat(self
, args
, "et:stat", STAT
, "U:stat", win32_wstat
);
2504 return posix_do_stat(self
, args
, "et:stat", STAT
, NULL
, NULL
);
2510 PyDoc_STRVAR(posix_system__doc__
,
2511 "system(command) -> exit_status\n\n\
2512 Execute the command (a string) in a subshell.");
2515 posix_system(PyObject
*self
, PyObject
*args
)
2519 if (!PyArg_ParseTuple(args
, "s:system", &command
))
2521 Py_BEGIN_ALLOW_THREADS
2522 sts
= system(command
);
2523 Py_END_ALLOW_THREADS
2524 return PyInt_FromLong(sts
);
2529 PyDoc_STRVAR(posix_umask__doc__
,
2530 "umask(new_mask) -> old_mask\n\n\
2531 Set the current numeric umask and return the previous umask.");
2534 posix_umask(PyObject
*self
, PyObject
*args
)
2537 if (!PyArg_ParseTuple(args
, "i:umask", &i
))
2541 return posix_error();
2542 return PyInt_FromLong((long)i
);
2546 PyDoc_STRVAR(posix_unlink__doc__
,
2548 Remove a file (same as remove(path)).");
2550 PyDoc_STRVAR(posix_remove__doc__
,
2552 Remove a file (same as unlink(path)).");
2555 posix_unlink(PyObject
*self
, PyObject
*args
)
2558 return win32_1str(args
, "remove", "s:remove", DeleteFileA
, "U:remove", DeleteFileW
);
2560 return posix_1str(args
, "et:remove", unlink
);
2566 PyDoc_STRVAR(posix_uname__doc__
,
2567 "uname() -> (sysname, nodename, release, version, machine)\n\n\
2568 Return a tuple identifying the current operating system.");
2571 posix_uname(PyObject
*self
, PyObject
*noargs
)
2576 Py_BEGIN_ALLOW_THREADS
2578 Py_END_ALLOW_THREADS
2580 return posix_error();
2581 return Py_BuildValue("(sssss)",
2588 #endif /* HAVE_UNAME */
2591 extract_time(PyObject
*t
, long* sec
, long* usec
)
2594 if (PyFloat_Check(t
)) {
2595 double tval
= PyFloat_AsDouble(t
);
2596 PyObject
*intobj
= t
->ob_type
->tp_as_number
->nb_int(t
);
2599 intval
= PyInt_AsLong(intobj
);
2601 if (intval
== -1 && PyErr_Occurred())
2604 *usec
= (long)((tval
- intval
) * 1e6
); /* can't exceed 1000000 */
2606 /* If rounding gave us a negative number,
2611 intval
= PyInt_AsLong(t
);
2612 if (intval
== -1 && PyErr_Occurred())
2619 PyDoc_STRVAR(posix_utime__doc__
,
2620 "utime(path, (atime, mtime))\n\
2621 utime(path, None)\n\n\
2622 Set the access and modified time of the file to the given values. If the\n\
2623 second form is used, set the access and modified times to the current time.");
2626 posix_utime(PyObject
*self
, PyObject
*args
)
2628 #ifdef Py_WIN_WIDE_FILENAMES
2630 PyUnicodeObject
*obwpath
;
2631 wchar_t *wpath
= NULL
;
2634 long atimesec
, mtimesec
, ausec
, musec
;
2635 FILETIME atime
, mtime
;
2636 PyObject
*result
= NULL
;
2638 if (unicode_file_names()) {
2639 if (PyArg_ParseTuple(args
, "UO|:utime", &obwpath
, &arg
)) {
2640 wpath
= PyUnicode_AS_UNICODE(obwpath
);
2641 Py_BEGIN_ALLOW_THREADS
2642 hFile
= CreateFileW(wpath
, FILE_WRITE_ATTRIBUTES
, 0,
2643 NULL
, OPEN_EXISTING
,
2644 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2645 Py_END_ALLOW_THREADS
2646 if (hFile
== INVALID_HANDLE_VALUE
)
2647 return win32_error_unicode("utime", wpath
);
2649 /* Drop the argument parsing error as narrow strings
2654 if (!PyArg_ParseTuple(args
, "etO:utime",
2655 Py_FileSystemDefaultEncoding
, &apath
, &arg
))
2657 Py_BEGIN_ALLOW_THREADS
2658 hFile
= CreateFileA(apath
, FILE_WRITE_ATTRIBUTES
, 0,
2659 NULL
, OPEN_EXISTING
,
2660 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2661 Py_END_ALLOW_THREADS
2662 if (hFile
== INVALID_HANDLE_VALUE
) {
2663 win32_error("utime", apath
);
2670 if (arg
== Py_None
) {
2672 GetSystemTime(&now
);
2673 if (!SystemTimeToFileTime(&now
, &mtime
) ||
2674 !SystemTimeToFileTime(&now
, &atime
)) {
2675 win32_error("utime", NULL
);
2679 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2680 PyErr_SetString(PyExc_TypeError
,
2681 "utime() arg 2 must be a tuple (atime, mtime)");
2685 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2686 &atimesec
, &ausec
) == -1)
2688 time_t_to_FILE_TIME(atimesec
, 1000*ausec
, &atime
);
2689 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2690 &mtimesec
, &musec
) == -1)
2692 time_t_to_FILE_TIME(mtimesec
, 1000*musec
, &mtime
);
2694 if (!SetFileTime(hFile
, NULL
, &atime
, &mtime
)) {
2695 /* Avoid putting the file name into the error here,
2696 as that may confuse the user into believing that
2697 something is wrong with the file, when it also
2698 could be the time stamp that gives a problem. */
2699 win32_error("utime", NULL
);
2706 #else /* Py_WIN_WIDE_FILENAMES */
2709 long atime
, mtime
, ausec
, musec
;
2713 #if defined(HAVE_UTIMES)
2714 struct timeval buf
[2];
2715 #define ATIME buf[0].tv_sec
2716 #define MTIME buf[1].tv_sec
2717 #elif defined(HAVE_UTIME_H)
2718 /* XXX should define struct utimbuf instead, above */
2720 #define ATIME buf.actime
2721 #define MTIME buf.modtime
2722 #define UTIME_ARG &buf
2723 #else /* HAVE_UTIMES */
2725 #define ATIME buf[0]
2726 #define MTIME buf[1]
2727 #define UTIME_ARG buf
2728 #endif /* HAVE_UTIMES */
2731 if (!PyArg_ParseTuple(args
, "etO:utime",
2732 Py_FileSystemDefaultEncoding
, &path
, &arg
))
2734 if (arg
== Py_None
) {
2735 /* optional time values not given */
2736 Py_BEGIN_ALLOW_THREADS
2737 res
= utime(path
, NULL
);
2738 Py_END_ALLOW_THREADS
2740 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2741 PyErr_SetString(PyExc_TypeError
,
2742 "utime() arg 2 must be a tuple (atime, mtime)");
2747 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2748 &atime
, &ausec
) == -1) {
2752 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2753 &mtime
, &musec
) == -1) {
2760 buf
[0].tv_usec
= ausec
;
2761 buf
[1].tv_usec
= musec
;
2762 Py_BEGIN_ALLOW_THREADS
2763 res
= utimes(path
, buf
);
2764 Py_END_ALLOW_THREADS
2766 Py_BEGIN_ALLOW_THREADS
2767 res
= utime(path
, UTIME_ARG
);
2768 Py_END_ALLOW_THREADS
2769 #endif /* HAVE_UTIMES */
2772 return posix_error_with_allocated_filename(path
);
2780 #endif /* Py_WIN_WIDE_FILENAMES */
2784 /* Process operations */
2786 PyDoc_STRVAR(posix__exit__doc__
,
2788 Exit to the system with specified status, without normal exit processing.");
2791 posix__exit(PyObject
*self
, PyObject
*args
)
2794 if (!PyArg_ParseTuple(args
, "i:_exit", &sts
))
2797 return NULL
; /* Make gcc -Wall happy */
2800 #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
2802 free_string_array(char **array
, Py_ssize_t count
)
2805 for (i
= 0; i
< count
; i
++)
2806 PyMem_Free(array
[i
]);
2813 PyDoc_STRVAR(posix_execv__doc__
,
2814 "execv(path, args)\n\n\
2815 Execute an executable path with arguments, replacing current process.\n\
2817 path: path of executable file\n\
2818 args: tuple or list of strings");
2821 posix_execv(PyObject
*self
, PyObject
*args
)
2827 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
2829 /* execv has two arguments: (path, argv), where
2830 argv is a list or tuple of strings. */
2832 if (!PyArg_ParseTuple(args
, "etO:execv",
2833 Py_FileSystemDefaultEncoding
,
2836 if (PyList_Check(argv
)) {
2837 argc
= PyList_Size(argv
);
2838 getitem
= PyList_GetItem
;
2840 else if (PyTuple_Check(argv
)) {
2841 argc
= PyTuple_Size(argv
);
2842 getitem
= PyTuple_GetItem
;
2845 PyErr_SetString(PyExc_TypeError
, "execv() arg 2 must be a tuple or list");
2850 argvlist
= PyMem_NEW(char *, argc
+1);
2851 if (argvlist
== NULL
) {
2853 return PyErr_NoMemory();
2855 for (i
= 0; i
< argc
; i
++) {
2856 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
2857 Py_FileSystemDefaultEncoding
,
2859 free_string_array(argvlist
, i
);
2860 PyErr_SetString(PyExc_TypeError
,
2861 "execv() arg 2 must contain only strings");
2867 argvlist
[argc
] = NULL
;
2869 execv(path
, argvlist
);
2871 /* If we get here it's definitely an error */
2873 free_string_array(argvlist
, argc
);
2875 return posix_error();
2879 PyDoc_STRVAR(posix_execve__doc__
,
2880 "execve(path, args, env)\n\n\
2881 Execute a path with arguments and environment, replacing current process.\n\
2883 path: path of executable file\n\
2884 args: tuple or list of arguments\n\
2885 env: dictionary of strings mapping to strings");
2888 posix_execve(PyObject
*self
, PyObject
*args
)
2891 PyObject
*argv
, *env
;
2894 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
;
2895 Py_ssize_t i
, pos
, argc
, envc
;
2896 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
2897 Py_ssize_t lastarg
= 0;
2899 /* execve has three arguments: (path, argv, env), where
2900 argv is a list or tuple of strings and env is a dictionary
2901 like posix.environ. */
2903 if (!PyArg_ParseTuple(args
, "etOO:execve",
2904 Py_FileSystemDefaultEncoding
,
2905 &path
, &argv
, &env
))
2907 if (PyList_Check(argv
)) {
2908 argc
= PyList_Size(argv
);
2909 getitem
= PyList_GetItem
;
2911 else if (PyTuple_Check(argv
)) {
2912 argc
= PyTuple_Size(argv
);
2913 getitem
= PyTuple_GetItem
;
2916 PyErr_SetString(PyExc_TypeError
,
2917 "execve() arg 2 must be a tuple or list");
2920 if (!PyMapping_Check(env
)) {
2921 PyErr_SetString(PyExc_TypeError
,
2922 "execve() arg 3 must be a mapping object");
2926 argvlist
= PyMem_NEW(char *, argc
+1);
2927 if (argvlist
== NULL
) {
2931 for (i
= 0; i
< argc
; i
++) {
2932 if (!PyArg_Parse((*getitem
)(argv
, i
),
2933 "et;execve() arg 2 must contain only strings",
2934 Py_FileSystemDefaultEncoding
,
2942 argvlist
[argc
] = NULL
;
2944 i
= PyMapping_Size(env
);
2947 envlist
= PyMem_NEW(char *, i
+ 1);
2948 if (envlist
== NULL
) {
2953 keys
= PyMapping_Keys(env
);
2954 vals
= PyMapping_Values(env
);
2957 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
2958 PyErr_SetString(PyExc_TypeError
,
2959 "execve(): env.keys() or env.values() is not a list");
2963 for (pos
= 0; pos
< i
; pos
++) {
2967 key
= PyList_GetItem(keys
, pos
);
2968 val
= PyList_GetItem(vals
, pos
);
2974 "s;execve() arg 3 contains a non-string key",
2978 "s;execve() arg 3 contains a non-string value",
2984 #if defined(PYOS_OS2)
2985 /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
2986 if (stricmp(k
, "BEGINLIBPATH") != 0 && stricmp(k
, "ENDLIBPATH") != 0) {
2988 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
2989 p
= PyMem_NEW(char, len
);
2994 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
2995 envlist
[envc
++] = p
;
2996 #if defined(PYOS_OS2)
3002 execve(path
, argvlist
, envlist
);
3004 /* If we get here it's definitely an error */
3006 (void) posix_error();
3010 PyMem_DEL(envlist
[envc
]);
3013 free_string_array(argvlist
, lastarg
);
3020 #endif /* HAVE_EXECV */
3024 PyDoc_STRVAR(posix_spawnv__doc__
,
3025 "spawnv(mode, path, args)\n\n\
3026 Execute the program 'path' in a new process.\n\
3028 mode: mode of process creation\n\
3029 path: path of executable file\n\
3030 args: tuple or list of strings");
3033 posix_spawnv(PyObject
*self
, PyObject
*args
)
3040 Py_intptr_t spawnval
;
3041 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3043 /* spawnv has three arguments: (mode, path, argv), where
3044 argv is a list or tuple of strings. */
3046 if (!PyArg_ParseTuple(args
, "ietO:spawnv", &mode
,
3047 Py_FileSystemDefaultEncoding
,
3050 if (PyList_Check(argv
)) {
3051 argc
= PyList_Size(argv
);
3052 getitem
= PyList_GetItem
;
3054 else if (PyTuple_Check(argv
)) {
3055 argc
= PyTuple_Size(argv
);
3056 getitem
= PyTuple_GetItem
;
3059 PyErr_SetString(PyExc_TypeError
,
3060 "spawnv() arg 2 must be a tuple or list");
3065 argvlist
= PyMem_NEW(char *, argc
+1);
3066 if (argvlist
== NULL
) {
3068 return PyErr_NoMemory();
3070 for (i
= 0; i
< argc
; i
++) {
3071 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3072 Py_FileSystemDefaultEncoding
,
3074 free_string_array(argvlist
, i
);
3077 "spawnv() arg 2 must contain only strings");
3082 argvlist
[argc
] = NULL
;
3084 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3085 Py_BEGIN_ALLOW_THREADS
3086 spawnval
= spawnv(mode
, path
, argvlist
);
3087 Py_END_ALLOW_THREADS
3089 if (mode
== _OLD_P_OVERLAY
)
3092 Py_BEGIN_ALLOW_THREADS
3093 spawnval
= _spawnv(mode
, path
, argvlist
);
3094 Py_END_ALLOW_THREADS
3097 free_string_array(argvlist
, argc
);
3101 return posix_error();
3103 #if SIZEOF_LONG == SIZEOF_VOID_P
3104 return Py_BuildValue("l", (long) spawnval
);
3106 return Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3111 PyDoc_STRVAR(posix_spawnve__doc__
,
3112 "spawnve(mode, path, args, env)\n\n\
3113 Execute the program 'path' in a new process.\n\
3115 mode: mode of process creation\n\
3116 path: path of executable file\n\
3117 args: tuple or list of arguments\n\
3118 env: dictionary of strings mapping to strings");
3121 posix_spawnve(PyObject
*self
, PyObject
*args
)
3124 PyObject
*argv
, *env
;
3127 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3128 int mode
, pos
, envc
;
3130 Py_intptr_t spawnval
;
3131 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3132 Py_ssize_t lastarg
= 0;
3134 /* spawnve has four arguments: (mode, path, argv, env), where
3135 argv is a list or tuple of strings and env is a dictionary
3136 like posix.environ. */
3138 if (!PyArg_ParseTuple(args
, "ietOO:spawnve", &mode
,
3139 Py_FileSystemDefaultEncoding
,
3140 &path
, &argv
, &env
))
3142 if (PyList_Check(argv
)) {
3143 argc
= PyList_Size(argv
);
3144 getitem
= PyList_GetItem
;
3146 else if (PyTuple_Check(argv
)) {
3147 argc
= PyTuple_Size(argv
);
3148 getitem
= PyTuple_GetItem
;
3151 PyErr_SetString(PyExc_TypeError
,
3152 "spawnve() arg 2 must be a tuple or list");
3155 if (!PyMapping_Check(env
)) {
3156 PyErr_SetString(PyExc_TypeError
,
3157 "spawnve() arg 3 must be a mapping object");
3161 argvlist
= PyMem_NEW(char *, argc
+1);
3162 if (argvlist
== NULL
) {
3166 for (i
= 0; i
< argc
; i
++) {
3167 if (!PyArg_Parse((*getitem
)(argv
, i
),
3168 "et;spawnve() arg 2 must contain only strings",
3169 Py_FileSystemDefaultEncoding
,
3177 argvlist
[argc
] = NULL
;
3179 i
= PyMapping_Size(env
);
3182 envlist
= PyMem_NEW(char *, i
+ 1);
3183 if (envlist
== NULL
) {
3188 keys
= PyMapping_Keys(env
);
3189 vals
= PyMapping_Values(env
);
3192 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3193 PyErr_SetString(PyExc_TypeError
,
3194 "spawnve(): env.keys() or env.values() is not a list");
3198 for (pos
= 0; pos
< i
; pos
++) {
3202 key
= PyList_GetItem(keys
, pos
);
3203 val
= PyList_GetItem(vals
, pos
);
3209 "s;spawnve() arg 3 contains a non-string key",
3213 "s;spawnve() arg 3 contains a non-string value",
3218 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3219 p
= PyMem_NEW(char, len
);
3224 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3225 envlist
[envc
++] = p
;
3229 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3230 Py_BEGIN_ALLOW_THREADS
3231 spawnval
= spawnve(mode
, path
, argvlist
, envlist
);
3232 Py_END_ALLOW_THREADS
3234 if (mode
== _OLD_P_OVERLAY
)
3237 Py_BEGIN_ALLOW_THREADS
3238 spawnval
= _spawnve(mode
, path
, argvlist
, envlist
);
3239 Py_END_ALLOW_THREADS
3243 (void) posix_error();
3245 #if SIZEOF_LONG == SIZEOF_VOID_P
3246 res
= Py_BuildValue("l", (long) spawnval
);
3248 res
= Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3253 PyMem_DEL(envlist
[envc
]);
3256 free_string_array(argvlist
, lastarg
);
3264 /* OS/2 supports spawnvp & spawnvpe natively */
3265 #if defined(PYOS_OS2)
3266 PyDoc_STRVAR(posix_spawnvp__doc__
,
3267 "spawnvp(mode, file, args)\n\n\
3268 Execute the program 'file' in a new process, using the environment\n\
3269 search path to find the file.\n\
3271 mode: mode of process creation\n\
3272 file: executable file name\n\
3273 args: tuple or list of strings");
3276 posix_spawnvp(PyObject
*self
, PyObject
*args
)
3282 Py_intptr_t spawnval
;
3283 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3285 /* spawnvp has three arguments: (mode, path, argv), where
3286 argv is a list or tuple of strings. */
3288 if (!PyArg_ParseTuple(args
, "ietO:spawnvp", &mode
,
3289 Py_FileSystemDefaultEncoding
,
3292 if (PyList_Check(argv
)) {
3293 argc
= PyList_Size(argv
);
3294 getitem
= PyList_GetItem
;
3296 else if (PyTuple_Check(argv
)) {
3297 argc
= PyTuple_Size(argv
);
3298 getitem
= PyTuple_GetItem
;
3301 PyErr_SetString(PyExc_TypeError
,
3302 "spawnvp() arg 2 must be a tuple or list");
3307 argvlist
= PyMem_NEW(char *, argc
+1);
3308 if (argvlist
== NULL
) {
3310 return PyErr_NoMemory();
3312 for (i
= 0; i
< argc
; i
++) {
3313 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3314 Py_FileSystemDefaultEncoding
,
3316 free_string_array(argvlist
, i
);
3319 "spawnvp() arg 2 must contain only strings");
3324 argvlist
[argc
] = NULL
;
3326 Py_BEGIN_ALLOW_THREADS
3327 #if defined(PYCC_GCC)
3328 spawnval
= spawnvp(mode
, path
, argvlist
);
3330 spawnval
= _spawnvp(mode
, path
, argvlist
);
3332 Py_END_ALLOW_THREADS
3334 free_string_array(argvlist
, argc
);
3338 return posix_error();
3340 return Py_BuildValue("l", (long) spawnval
);
3344 PyDoc_STRVAR(posix_spawnvpe__doc__
,
3345 "spawnvpe(mode, file, args, env)\n\n\
3346 Execute the program 'file' in a new process, using the environment\n\
3347 search path to find the file.\n\
3349 mode: mode of process creation\n\
3350 file: executable file name\n\
3351 args: tuple or list of arguments\n\
3352 env: dictionary of strings mapping to strings");
3355 posix_spawnvpe(PyObject
*self
, PyObject
*args
)
3358 PyObject
*argv
, *env
;
3361 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3362 int mode
, i
, pos
, argc
, envc
;
3363 Py_intptr_t spawnval
;
3364 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3367 /* spawnvpe has four arguments: (mode, path, argv, env), where
3368 argv is a list or tuple of strings and env is a dictionary
3369 like posix.environ. */
3371 if (!PyArg_ParseTuple(args
, "ietOO:spawnvpe", &mode
,
3372 Py_FileSystemDefaultEncoding
,
3373 &path
, &argv
, &env
))
3375 if (PyList_Check(argv
)) {
3376 argc
= PyList_Size(argv
);
3377 getitem
= PyList_GetItem
;
3379 else if (PyTuple_Check(argv
)) {
3380 argc
= PyTuple_Size(argv
);
3381 getitem
= PyTuple_GetItem
;
3384 PyErr_SetString(PyExc_TypeError
,
3385 "spawnvpe() arg 2 must be a tuple or list");
3388 if (!PyMapping_Check(env
)) {
3389 PyErr_SetString(PyExc_TypeError
,
3390 "spawnvpe() arg 3 must be a mapping object");
3394 argvlist
= PyMem_NEW(char *, argc
+1);
3395 if (argvlist
== NULL
) {
3399 for (i
= 0; i
< argc
; i
++) {
3400 if (!PyArg_Parse((*getitem
)(argv
, i
),
3401 "et;spawnvpe() arg 2 must contain only strings",
3402 Py_FileSystemDefaultEncoding
,
3410 argvlist
[argc
] = NULL
;
3412 i
= PyMapping_Size(env
);
3415 envlist
= PyMem_NEW(char *, i
+ 1);
3416 if (envlist
== NULL
) {
3421 keys
= PyMapping_Keys(env
);
3422 vals
= PyMapping_Values(env
);
3425 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3426 PyErr_SetString(PyExc_TypeError
,
3427 "spawnvpe(): env.keys() or env.values() is not a list");
3431 for (pos
= 0; pos
< i
; pos
++) {
3435 key
= PyList_GetItem(keys
, pos
);
3436 val
= PyList_GetItem(vals
, pos
);
3442 "s;spawnvpe() arg 3 contains a non-string key",
3446 "s;spawnvpe() arg 3 contains a non-string value",
3451 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3452 p
= PyMem_NEW(char, len
);
3457 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3458 envlist
[envc
++] = p
;
3462 Py_BEGIN_ALLOW_THREADS
3463 #if defined(PYCC_GCC)
3464 spawnval
= spawnve(mode
, path
, argvlist
, envlist
);
3466 spawnval
= _spawnve(mode
, path
, argvlist
, envlist
);
3468 Py_END_ALLOW_THREADS
3471 (void) posix_error();
3473 res
= Py_BuildValue("l", (long) spawnval
);
3477 PyMem_DEL(envlist
[envc
]);
3480 free_string_array(argvlist
, lastarg
);
3487 #endif /* PYOS_OS2 */
3488 #endif /* HAVE_SPAWNV */
3492 PyDoc_STRVAR(posix_fork1__doc__
,
3493 "fork1() -> pid\n\n\
3494 Fork a child process with a single multiplexed (i.e., not bound) thread.\n\
3496 Return 0 to child process and PID of child to parent process.");
3499 posix_fork1(PyObject
*self
, PyObject
*noargs
)
3503 return posix_error();
3505 return PyInt_FromLong((long)pid
);
3511 PyDoc_STRVAR(posix_fork__doc__
,
3513 Fork a child process.\n\
3514 Return 0 to child process and PID of child to parent process.");
3517 posix_fork(PyObject
*self
, PyObject
*noargs
)
3521 return posix_error();
3524 return PyInt_FromLong((long)pid
);
3528 /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
3529 /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
3530 #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
3531 #define DEV_PTY_FILE "/dev/ptc"
3532 #define HAVE_DEV_PTMX
3534 #define DEV_PTY_FILE "/dev/ptmx"
3537 #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
3541 #ifdef HAVE_LIBUTIL_H
3542 #include <libutil.h>
3543 #endif /* HAVE_LIBUTIL_H */
3544 #endif /* HAVE_PTY_H */
3545 #ifdef HAVE_STROPTS_H
3546 #include <stropts.h>
3548 #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
3550 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
3551 PyDoc_STRVAR(posix_openpty__doc__
,
3552 "openpty() -> (master_fd, slave_fd)\n\n\
3553 Open a pseudo-terminal, returning open fd's for both master and slave end.\n");
3556 posix_openpty(PyObject
*self
, PyObject
*noargs
)
3558 int master_fd
, slave_fd
;
3559 #ifndef HAVE_OPENPTY
3562 #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
3563 PyOS_sighandler_t sig_saved
;
3565 extern char *ptsname(int fildes
);
3570 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) != 0)
3571 return posix_error();
3572 #elif defined(HAVE__GETPTY)
3573 slave_name
= _getpty(&master_fd
, O_RDWR
, 0666, 0);
3574 if (slave_name
== NULL
)
3575 return posix_error();
3577 slave_fd
= open(slave_name
, O_RDWR
);
3579 return posix_error();
3581 master_fd
= open(DEV_PTY_FILE
, O_RDWR
| O_NOCTTY
); /* open master */
3583 return posix_error();
3584 sig_saved
= PyOS_setsig(SIGCHLD
, SIG_DFL
);
3585 /* change permission of slave */
3586 if (grantpt(master_fd
) < 0) {
3587 PyOS_setsig(SIGCHLD
, sig_saved
);
3588 return posix_error();
3591 if (unlockpt(master_fd
) < 0) {
3592 PyOS_setsig(SIGCHLD
, sig_saved
);
3593 return posix_error();
3595 PyOS_setsig(SIGCHLD
, sig_saved
);
3596 slave_name
= ptsname(master_fd
); /* get name of slave */
3597 if (slave_name
== NULL
)
3598 return posix_error();
3599 slave_fd
= open(slave_name
, O_RDWR
| O_NOCTTY
); /* open slave */
3601 return posix_error();
3602 #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
3603 ioctl(slave_fd
, I_PUSH
, "ptem"); /* push ptem */
3604 ioctl(slave_fd
, I_PUSH
, "ldterm"); /* push ldterm */
3606 ioctl(slave_fd
, I_PUSH
, "ttcompat"); /* push ttcompat */
3608 #endif /* HAVE_CYGWIN */
3609 #endif /* HAVE_OPENPTY */
3611 return Py_BuildValue("(ii)", master_fd
, slave_fd
);
3614 #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
3617 PyDoc_STRVAR(posix_forkpty__doc__
,
3618 "forkpty() -> (pid, master_fd)\n\n\
3619 Fork a new process with a new pseudo-terminal as controlling tty.\n\n\
3620 Like fork(), return 0 as pid to child process, and PID of child to parent.\n\
3621 To both, return fd of newly opened pseudo-terminal.\n");
3624 posix_forkpty(PyObject
*self
, PyObject
*noargs
)
3626 int master_fd
= -1, pid
;
3628 pid
= forkpty(&master_fd
, NULL
, NULL
, NULL
);
3630 return posix_error();
3633 return Py_BuildValue("(ii)", pid
, master_fd
);
3638 PyDoc_STRVAR(posix_getegid__doc__
,
3639 "getegid() -> egid\n\n\
3640 Return the current process's effective group id.");
3643 posix_getegid(PyObject
*self
, PyObject
*noargs
)
3645 return PyInt_FromLong((long)getegid());
3651 PyDoc_STRVAR(posix_geteuid__doc__
,
3652 "geteuid() -> euid\n\n\
3653 Return the current process's effective user id.");
3656 posix_geteuid(PyObject
*self
, PyObject
*noargs
)
3658 return PyInt_FromLong((long)geteuid());
3664 PyDoc_STRVAR(posix_getgid__doc__
,
3665 "getgid() -> gid\n\n\
3666 Return the current process's group id.");
3669 posix_getgid(PyObject
*self
, PyObject
*noargs
)
3671 return PyInt_FromLong((long)getgid());
3676 PyDoc_STRVAR(posix_getpid__doc__
,
3677 "getpid() -> pid\n\n\
3678 Return the current process id");
3681 posix_getpid(PyObject
*self
, PyObject
*noargs
)
3683 return PyInt_FromLong((long)getpid());
3687 #ifdef HAVE_GETGROUPS
3688 PyDoc_STRVAR(posix_getgroups__doc__
,
3689 "getgroups() -> list of group IDs\n\n\
3690 Return list of supplemental group IDs for the process.");
3693 posix_getgroups(PyObject
*self
, PyObject
*noargs
)
3695 PyObject
*result
= NULL
;
3698 #define MAX_GROUPS NGROUPS_MAX
3700 /* defined to be 16 on Solaris7, so this should be a small number */
3701 #define MAX_GROUPS 64
3703 gid_t grouplist
[MAX_GROUPS
];
3706 n
= getgroups(MAX_GROUPS
, grouplist
);
3710 result
= PyList_New(n
);
3711 if (result
!= NULL
) {
3713 for (i
= 0; i
< n
; ++i
) {
3714 PyObject
*o
= PyInt_FromLong((long)grouplist
[i
]);
3720 PyList_SET_ITEM(result
, i
, o
);
3730 PyDoc_STRVAR(posix_getpgid__doc__
,
3731 "getpgid(pid) -> pgid\n\n\
3732 Call the system call getpgid().");
3735 posix_getpgid(PyObject
*self
, PyObject
*args
)
3738 if (!PyArg_ParseTuple(args
, "i:getpgid", &pid
))
3740 pgid
= getpgid(pid
);
3742 return posix_error();
3743 return PyInt_FromLong((long)pgid
);
3745 #endif /* HAVE_GETPGID */
3749 PyDoc_STRVAR(posix_getpgrp__doc__
,
3750 "getpgrp() -> pgrp\n\n\
3751 Return the current process group id.");
3754 posix_getpgrp(PyObject
*self
, PyObject
*noargs
)
3756 #ifdef GETPGRP_HAVE_ARG
3757 return PyInt_FromLong((long)getpgrp(0));
3758 #else /* GETPGRP_HAVE_ARG */
3759 return PyInt_FromLong((long)getpgrp());
3760 #endif /* GETPGRP_HAVE_ARG */
3762 #endif /* HAVE_GETPGRP */
3766 PyDoc_STRVAR(posix_setpgrp__doc__
,
3768 Make this process a session leader.");
3771 posix_setpgrp(PyObject
*self
, PyObject
*noargs
)
3773 #ifdef SETPGRP_HAVE_ARG
3774 if (setpgrp(0, 0) < 0)
3775 #else /* SETPGRP_HAVE_ARG */
3777 #endif /* SETPGRP_HAVE_ARG */
3778 return posix_error();
3783 #endif /* HAVE_SETPGRP */
3786 PyDoc_STRVAR(posix_getppid__doc__
,
3787 "getppid() -> ppid\n\n\
3788 Return the parent's process id.");
3791 posix_getppid(PyObject
*self
, PyObject
*noargs
)
3793 return PyInt_FromLong((long)getppid());
3798 #ifdef HAVE_GETLOGIN
3799 PyDoc_STRVAR(posix_getlogin__doc__
,
3800 "getlogin() -> string\n\n\
3801 Return the actual login name.");
3804 posix_getlogin(PyObject
*self
, PyObject
*noargs
)
3806 PyObject
*result
= NULL
;
3808 int old_errno
= errno
;
3816 PyErr_SetString(PyExc_OSError
,
3817 "unable to determine login name");
3820 result
= PyString_FromString(name
);
3828 PyDoc_STRVAR(posix_getuid__doc__
,
3829 "getuid() -> uid\n\n\
3830 Return the current process's user id.");
3833 posix_getuid(PyObject
*self
, PyObject
*noargs
)
3835 return PyInt_FromLong((long)getuid());
3841 PyDoc_STRVAR(posix_kill__doc__
,
3842 "kill(pid, sig)\n\n\
3843 Kill a process with a signal.");
3846 posix_kill(PyObject
*self
, PyObject
*args
)
3849 if (!PyArg_ParseTuple(args
, "ii:kill", &pid
, &sig
))
3851 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
3852 if (sig
== XCPT_SIGNAL_INTR
|| sig
== XCPT_SIGNAL_BREAK
) {
3854 if ((rc
= DosSendSignalException(pid
, sig
)) != NO_ERROR
)
3855 return os2_error(rc
);
3857 } else if (sig
== XCPT_SIGNAL_KILLPROC
) {
3859 if ((rc
= DosKillProcess(DKP_PROCESS
, pid
)) != NO_ERROR
)
3860 return os2_error(rc
);
3863 return NULL
; /* Unrecognized Signal Requested */
3865 if (kill(pid
, sig
) == -1)
3866 return posix_error();
3874 PyDoc_STRVAR(posix_killpg__doc__
,
3875 "killpg(pgid, sig)\n\n\
3876 Kill a process group with a signal.");
3879 posix_killpg(PyObject
*self
, PyObject
*args
)
3882 if (!PyArg_ParseTuple(args
, "ii:killpg", &pgid
, &sig
))
3884 if (killpg(pgid
, sig
) == -1)
3885 return posix_error();
3893 #ifdef HAVE_SYS_LOCK_H
3894 #include <sys/lock.h>
3897 PyDoc_STRVAR(posix_plock__doc__
,
3899 Lock program segments into memory.");
3902 posix_plock(PyObject
*self
, PyObject
*args
)
3905 if (!PyArg_ParseTuple(args
, "i:plock", &op
))
3907 if (plock(op
) == -1)
3908 return posix_error();
3916 PyDoc_STRVAR(posix_popen__doc__
,
3917 "popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\
3918 Open a pipe to/from a command returning a file object.");
3920 #if defined(PYOS_OS2)
3921 #if defined(PYCC_VACPP)
3923 async_system(const char *command
)
3925 char errormsg
[256], args
[1024];
3929 char *shell
= getenv("COMSPEC");
3933 /* avoid overflowing the argument buffer */
3934 if (strlen(shell
) + 3 + strlen(command
) >= 1024)
3935 return ERROR_NOT_ENOUGH_MEMORY
3938 strcat(args
, shell
);
3939 strcat(args
, "/c ");
3940 strcat(args
, command
);
3942 /* execute asynchronously, inheriting the environment */
3943 rc
= DosExecPgm(errormsg
,
3954 popen(const char *command
, const char *mode
, int pipesize
, int *err
)
3960 /* mode determines which of stdin or stdout is reconnected to
3961 * the pipe to the child
3963 if (strchr(mode
, 'r') != NULL
) {
3964 tgt_fd
= 1; /* stdout */
3965 } else if (strchr(mode
, 'w')) {
3966 tgt_fd
= 0; /* stdin */
3968 *err
= ERROR_INVALID_ACCESS
;
3972 /* setup the pipe */
3973 if ((rc
= DosCreatePipe(&pipeh
[0], &pipeh
[1], pipesize
)) != NO_ERROR
) {
3978 /* prevent other threads accessing stdio */
3981 /* reconnect stdio and execute child */
3984 if (dup2(pipeh
[tgtfd
], tgtfd
) == 0) {
3985 DosClose(pipeh
[tgtfd
]);
3986 rc
= async_system(command
);
3993 /* allow other threads access to stdio */
3996 /* if execution of child was successful return file stream */
3998 return fdopen(pipeh
[1 - tgtfd
], mode
);
4000 DosClose(pipeh
[1 - tgtfd
]);
4007 posix_popen(PyObject
*self
, PyObject
*args
)
4011 int err
, bufsize
= -1;
4014 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4016 Py_BEGIN_ALLOW_THREADS
4017 fp
= popen(name
, mode
, (bufsize
> 0) ? bufsize
: 4096, &err
);
4018 Py_END_ALLOW_THREADS
4020 return os2_error(err
);
4022 f
= PyFile_FromFile(fp
, name
, mode
, fclose
);
4024 PyFile_SetBufSize(f
, bufsize
);
4028 #elif defined(PYCC_GCC)
4030 /* standard posix version of popen() support */
4032 posix_popen(PyObject
*self
, PyObject
*args
)
4039 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4041 Py_BEGIN_ALLOW_THREADS
4042 fp
= popen(name
, mode
);
4043 Py_END_ALLOW_THREADS
4045 return posix_error();
4046 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
4048 PyFile_SetBufSize(f
, bufsize
);
4052 /* fork() under OS/2 has lots'o'warts
4053 * EMX supports pipe() and spawn*() so we can synthesize popen[234]()
4054 * most of this code is a ripoff of the win32 code, but using the
4055 * capabilities of EMX's C library routines
4058 /* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */
4064 static PyObject
*_PyPopen(char *, int, int, int);
4065 static int _PyPclose(FILE *file
);
4068 * Internal dictionary mapping popen* file pointers to process handles,
4069 * for use when retrieving the process exit code. See _PyPclose() below
4070 * for more information on this dictionary's use.
4072 static PyObject
*_PyPopenProcs
= NULL
;
4074 /* os2emx version of popen2()
4076 * The result of this function is a pipe (file) connected to the
4077 * process's stdin, and a pipe connected to the process's stdout.
4081 os2emx_popen2(PyObject
*self
, PyObject
*args
)
4089 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4094 else if (*mode
!= 'b') {
4095 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4100 f
= _PyPopen(cmdstring
, tm
, POPEN_2
, bufsize
);
4106 * Variation on os2emx.popen2
4108 * The result of this function is 3 pipes - the process's stdin,
4113 os2emx_popen3(PyObject
*self
, PyObject
*args
)
4121 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4126 else if (*mode
!= 'b') {
4127 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4132 f
= _PyPopen(cmdstring
, tm
, POPEN_3
, bufsize
);
4138 * Variation on os2emx.popen2
4140 * The result of this function is 2 pipes - the processes stdin,
4141 * and stdout+stderr combined as a single pipe.
4145 os2emx_popen4(PyObject
*self
, PyObject
*args
)
4153 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4158 else if (*mode
!= 'b') {
4159 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4164 f
= _PyPopen(cmdstring
, tm
, POPEN_4
, bufsize
);
4169 /* a couple of structures for convenient handling of multiple
4170 * file handles and pipes
4184 /* The following code is derived from the win32 code */
4187 _PyPopen(char *cmdstring
, int mode
, int n
, int bufsize
)
4189 struct file_ref stdio
[3];
4190 struct pipe_ref p_fd
[3];
4192 int file_count
, i
, pipe_err
, pipe_pid
;
4193 char *shell
, *sh_name
, *opt
, *rd_mode
, *wr_mode
;
4194 PyObject
*f
, *p_f
[3];
4196 /* file modes for subsequent fdopen's on pipe handles */
4208 /* prepare shell references */
4209 if ((shell
= getenv("EMXSHELL")) == NULL
)
4210 if ((shell
= getenv("COMSPEC")) == NULL
)
4213 return posix_error();
4216 sh_name
= _getname(shell
);
4217 if (stricmp(sh_name
, "cmd.exe") == 0 || stricmp(sh_name
, "4os2.exe") == 0)
4222 /* save current stdio fds + their flags, and set not inheritable */
4224 while (pipe_err
>= 0 && i
< 3)
4226 pipe_err
= stdio
[i
].handle
= dup(i
);
4227 stdio
[i
].flags
= fcntl(i
, F_GETFD
, 0);
4228 fcntl(stdio
[i
].handle
, F_SETFD
, stdio
[i
].flags
| FD_CLOEXEC
);
4233 /* didn't get them all saved - clean up and bail out */
4234 int saved_err
= errno
;
4237 close(stdio
[i
].handle
);
4240 return posix_error();
4243 /* create pipe ends */
4248 while ((pipe_err
== 0) && (i
< file_count
))
4249 pipe_err
= pipe((int *)&p_fd
[i
++]);
4252 /* didn't get them all made - clean up and bail out */
4259 return posix_error();
4262 /* change the actual standard IO streams over temporarily,
4263 * making the retained pipe ends non-inheritable
4268 if (dup2(p_fd
[0].rd
, 0) == 0)
4271 i
= fcntl(p_fd
[0].wr
, F_GETFD
, 0);
4272 fcntl(p_fd
[0].wr
, F_SETFD
, i
| FD_CLOEXEC
);
4273 if ((p_s
[0] = fdopen(p_fd
[0].wr
, wr_mode
)) == NULL
)
4287 if (dup2(p_fd
[1].wr
, 1) == 1)
4290 i
= fcntl(p_fd
[1].rd
, F_GETFD
, 0);
4291 fcntl(p_fd
[1].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4292 if ((p_s
[1] = fdopen(p_fd
[1].rd
, rd_mode
)) == NULL
)
4304 /* - stderr, as required */
4310 if (dup2(p_fd
[2].wr
, 2) == 2)
4313 i
= fcntl(p_fd
[2].rd
, F_GETFD
, 0);
4314 fcntl(p_fd
[2].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4315 if ((p_s
[2] = fdopen(p_fd
[2].rd
, rd_mode
)) == NULL
)
4330 if (dup2(1, 2) != 2)
4338 /* spawn the child process */
4341 pipe_pid
= spawnlp(P_NOWAIT
, shell
, shell
, opt
, cmdstring
, (char *)0);
4348 /* save the PID into the FILE structure
4349 * NOTE: this implementation doesn't actually
4350 * take advantage of this, but do it for
4351 * completeness - AIM Apr01
4353 for (i
= 0; i
< file_count
; i
++)
4354 p_s
[i
]->_pid
= pipe_pid
;
4358 /* reset standard IO to normal */
4359 for (i
= 0; i
< 3; i
++)
4361 dup2(stdio
[i
].handle
, i
);
4362 fcntl(i
, F_SETFD
, stdio
[i
].flags
);
4363 close(stdio
[i
].handle
);
4366 /* if any remnant problems, clean up and bail out */
4369 for (i
= 0; i
< 3; i
++)
4375 return posix_error_with_filename(cmdstring
);
4378 /* build tuple of file objects to return */
4379 if ((p_f
[0] = PyFile_FromFile(p_s
[0], cmdstring
, wr_mode
, _PyPclose
)) != NULL
)
4380 PyFile_SetBufSize(p_f
[0], bufsize
);
4381 if ((p_f
[1] = PyFile_FromFile(p_s
[1], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4382 PyFile_SetBufSize(p_f
[1], bufsize
);
4385 if ((p_f
[2] = PyFile_FromFile(p_s
[2], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4386 PyFile_SetBufSize(p_f
[0], bufsize
);
4387 f
= PyTuple_Pack(3, p_f
[0], p_f
[1], p_f
[2]);
4390 f
= PyTuple_Pack(2, p_f
[0], p_f
[1]);
4393 * Insert the files we've created into the process dictionary
4394 * all referencing the list with the process handle and the
4395 * initial number of files (see description below in _PyPclose).
4396 * Since if _PyPclose later tried to wait on a process when all
4397 * handles weren't closed, it could create a deadlock with the
4398 * child, we spend some energy here to try to ensure that we
4399 * either insert all file handles into the dictionary or none
4400 * at all. It's a little clumsy with the various popen modes
4401 * and variable number of files involved.
4405 _PyPopenProcs
= PyDict_New();
4410 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
[3];
4413 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
4414 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
4416 procObj
= PyList_New(2);
4417 pidObj
= PyInt_FromLong((long) pipe_pid
);
4418 intObj
= PyInt_FromLong((long) file_count
);
4420 if (procObj
&& pidObj
&& intObj
)
4422 PyList_SetItem(procObj
, 0, pidObj
);
4423 PyList_SetItem(procObj
, 1, intObj
);
4425 fileObj
[0] = PyLong_FromVoidPtr(p_s
[0]);
4428 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
4432 fileObj
[1] = PyLong_FromVoidPtr(p_s
[1]);
4435 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
4439 if (file_count
>= 3)
4441 fileObj
[2] = PyLong_FromVoidPtr(p_s
[2]);
4444 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
4450 if (ins_rc
[0] < 0 || !fileObj
[0] ||
4451 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
4452 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2]))
4454 /* Something failed - remove any dictionary
4455 * entries that did make it.
4457 if (!ins_rc
[0] && fileObj
[0])
4459 PyDict_DelItem(_PyPopenProcs
,
4462 if (!ins_rc
[1] && fileObj
[1])
4464 PyDict_DelItem(_PyPopenProcs
,
4467 if (!ins_rc
[2] && fileObj
[2])
4469 PyDict_DelItem(_PyPopenProcs
,
4476 * Clean up our localized references for the dictionary keys
4477 * and value since PyDict_SetItem will Py_INCREF any copies
4478 * that got placed in the dictionary.
4480 Py_XDECREF(procObj
);
4481 Py_XDECREF(fileObj
[0]);
4482 Py_XDECREF(fileObj
[1]);
4483 Py_XDECREF(fileObj
[2]);
4486 /* Child is launched. */
4491 * Wrapper for fclose() to use for popen* files, so we can retrieve the
4492 * exit code for the child process and return as a result of the close.
4494 * This function uses the _PyPopenProcs dictionary in order to map the
4495 * input file pointer to information about the process that was
4496 * originally created by the popen* call that created the file pointer.
4497 * The dictionary uses the file pointer as a key (with one entry
4498 * inserted for each file returned by the original popen* call) and a
4499 * single list object as the value for all files from a single call.
4500 * The list object contains the Win32 process handle at [0], and a file
4501 * count at [1], which is initialized to the total number of file
4502 * handles using that list.
4504 * This function closes whichever handle it is passed, and decrements
4505 * the file count in the dictionary for the process handle pointed to
4506 * by this file. On the last close (when the file count reaches zero),
4507 * this function will wait for the child process and then return its
4508 * exit code as the result of the close() operation. This permits the
4509 * files to be closed in any order - it is always the close() of the
4510 * final handle that will return the exit code.
4512 * NOTE: This function is currently called with the GIL released.
4513 * hence we use the GILState API to manage our state.
4516 static int _PyPclose(FILE *file
)
4521 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
;
4524 PyGILState_STATE state
;
4527 /* Close the file handle first, to ensure it can't block the
4528 * child from exiting if it's the last handle.
4530 result
= fclose(file
);
4533 state
= PyGILState_Ensure();
4537 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
4538 (procObj
= PyDict_GetItem(_PyPopenProcs
,
4539 fileObj
)) != NULL
&&
4540 (pidObj
= PyList_GetItem(procObj
,0)) != NULL
&&
4541 (intObj
= PyList_GetItem(procObj
,1)) != NULL
)
4543 pipe_pid
= (int) PyInt_AsLong(pidObj
);
4544 file_count
= (int) PyInt_AsLong(intObj
);
4548 /* Still other files referencing process */
4550 PyList_SetItem(procObj
,1,
4551 PyInt_FromLong((long) file_count
));
4555 /* Last file for this process */
4556 if (result
!= EOF
&&
4557 waitpid(pipe_pid
, &exit_code
, 0) == pipe_pid
)
4559 /* extract exit status */
4560 if (WIFEXITED(exit_code
))
4562 result
= WEXITSTATUS(exit_code
);
4572 /* Indicate failure - this will cause the file object
4573 * to raise an I/O error and translate the last
4574 * error code from errno. We do have a problem with
4575 * last errors that overlap the normal errno table,
4576 * but that's a consistent problem with the file object.
4582 /* Remove this file pointer from dictionary */
4583 PyDict_DelItem(_PyPopenProcs
, fileObj
);
4585 if (PyDict_Size(_PyPopenProcs
) == 0)
4587 Py_DECREF(_PyPopenProcs
);
4588 _PyPopenProcs
= NULL
;
4591 } /* if object retrieval ok */
4593 Py_XDECREF(fileObj
);
4594 } /* if _PyPopenProcs */
4597 PyGILState_Release(state
);
4602 #endif /* PYCC_??? */
4604 #elif defined(MS_WINDOWS)
4607 * Portable 'popen' replacement for Win32.
4609 * Written by Bill Tutt <billtut@microsoft.com>. Minor tweaks
4610 * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>
4611 * Return code handling by David Bolen <db3l@fitlinxx.com>.
4618 /* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */
4624 static PyObject
*_PyPopen(char *, int, int);
4625 static int _PyPclose(FILE *file
);
4628 * Internal dictionary mapping popen* file pointers to process handles,
4629 * for use when retrieving the process exit code. See _PyPclose() below
4630 * for more information on this dictionary's use.
4632 static PyObject
*_PyPopenProcs
= NULL
;
4635 /* popen that works from a GUI.
4637 * The result of this function is a pipe (file) connected to the
4638 * processes stdin or stdout, depending on the requested mode.
4642 posix_popen(PyObject
*self
, PyObject
*args
)
4650 if (!PyArg_ParseTuple(args
, "s|si:popen", &cmdstring
, &mode
, &bufsize
))
4655 else if (*mode
!= 'w') {
4656 PyErr_SetString(PyExc_ValueError
, "popen() arg 2 must be 'r' or 'w'");
4661 if (bufsize
!= -1) {
4662 PyErr_SetString(PyExc_ValueError
, "popen() arg 3 must be -1");
4666 if (*(mode
+1) == 't')
4667 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4668 else if (*(mode
+1) == 'b')
4669 f
= _PyPopen(cmdstring
, tm
| _O_BINARY
, POPEN_1
);
4671 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4676 /* Variation on win32pipe.popen
4678 * The result of this function is a pipe (file) connected to the
4679 * process's stdin, and a pipe connected to the process's stdout.
4683 win32_popen2(PyObject
*self
, PyObject
*args
)
4691 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4696 else if (*mode
!= 'b') {
4697 PyErr_SetString(PyExc_ValueError
, "popen2() arg 2 must be 't' or 'b'");
4702 if (bufsize
!= -1) {
4703 PyErr_SetString(PyExc_ValueError
, "popen2() arg 3 must be -1");
4707 f
= _PyPopen(cmdstring
, tm
, POPEN_2
);
4713 * Variation on <om win32pipe.popen>
4715 * The result of this function is 3 pipes - the process's stdin,
4720 win32_popen3(PyObject
*self
, PyObject
*args
)
4728 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4733 else if (*mode
!= 'b') {
4734 PyErr_SetString(PyExc_ValueError
, "popen3() arg 2 must be 't' or 'b'");
4739 if (bufsize
!= -1) {
4740 PyErr_SetString(PyExc_ValueError
, "popen3() arg 3 must be -1");
4744 f
= _PyPopen(cmdstring
, tm
, POPEN_3
);
4750 * Variation on win32pipe.popen
4752 * The result of this function is 2 pipes - the processes stdin,
4753 * and stdout+stderr combined as a single pipe.
4757 win32_popen4(PyObject
*self
, PyObject
*args
)
4765 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4770 else if (*mode
!= 'b') {
4771 PyErr_SetString(PyExc_ValueError
, "popen4() arg 2 must be 't' or 'b'");
4776 if (bufsize
!= -1) {
4777 PyErr_SetString(PyExc_ValueError
, "popen4() arg 3 must be -1");
4781 f
= _PyPopen(cmdstring
, tm
, POPEN_4
);
4787 _PyPopenCreateProcess(char *cmdstring
,
4793 PROCESS_INFORMATION piProcInfo
;
4794 STARTUPINFO siStartInfo
;
4795 DWORD dwProcessFlags
= 0; /* no NEW_CONSOLE by default for Ctrl+C handling */
4796 char *s1
,*s2
, *s3
= " /c ";
4797 const char *szConsoleSpawn
= "w9xpopen.exe";
4801 if (i
= GetEnvironmentVariable("COMSPEC",NULL
,0)) {
4804 s1
= (char *)alloca(i
);
4805 if (!(x
= GetEnvironmentVariable("COMSPEC", s1
, i
)))
4806 /* x < i, so x fits into an integer */
4809 /* Explicitly check if we are using COMMAND.COM. If we are
4810 * then use the w9xpopen hack.
4813 while (comshell
>= s1
&& *comshell
!= '\\')
4817 if (GetVersion() < 0x80000000 &&
4818 _stricmp(comshell
, "command.com") != 0) {
4819 /* NT/2000 and not using command.com. */
4820 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1;
4821 s2
= (char *)alloca(x
);
4823 PyOS_snprintf(s2
, x
, "%s%s%s", s1
, s3
, cmdstring
);
4827 * Oh gag, we're on Win9x or using COMMAND.COM. Use
4828 * the workaround listed in KB: Q150956
4830 char modulepath
[_MAX_PATH
];
4831 struct stat statinfo
;
4832 GetModuleFileName(NULL
, modulepath
, sizeof(modulepath
));
4833 for (x
= i
= 0; modulepath
[i
]; i
++)
4834 if (modulepath
[i
] == SEP
)
4836 modulepath
[x
] = '\0';
4837 /* Create the full-name to w9xpopen, so we can test it exists */
4840 (sizeof(modulepath
)/sizeof(modulepath
[0]))
4841 -strlen(modulepath
));
4842 if (stat(modulepath
, &statinfo
) != 0) {
4843 size_t mplen
= sizeof(modulepath
)/sizeof(modulepath
[0]);
4844 /* Eeek - file-not-found - possibly an embedding
4845 situation - see if we can locate it in sys.prefix
4850 modulepath
[mplen
-1] = '\0';
4851 if (modulepath
[strlen(modulepath
)-1] != '\\')
4852 strcat(modulepath
, "\\");
4855 mplen
-strlen(modulepath
));
4856 /* No where else to look - raise an easily identifiable
4857 error, rather than leaving Windows to report
4858 "file not found" - as the user is probably blissfully
4859 unaware this shim EXE is used, and it will confuse them.
4860 (well, it confused me for a while ;-)
4862 if (stat(modulepath
, &statinfo
) != 0) {
4863 PyErr_Format(PyExc_RuntimeError
,
4864 "Can not locate '%s' which is needed "
4865 "for popen to work with your shell "
4871 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1 +
4872 strlen(modulepath
) +
4873 strlen(szConsoleSpawn
) + 1;
4875 s2
= (char *)alloca(x
);
4877 /* To maintain correct argument passing semantics,
4878 we pass the command-line as it stands, and allow
4879 quoting to be applied. w9xpopen.exe will then
4880 use its argv vector, and re-quote the necessary
4881 args for the ultimate child process.
4890 /* Not passing CREATE_NEW_CONSOLE has been known to
4891 cause random failures on win9x. Specifically a
4893 "Your program accessed mem currently in use at xxx"
4894 and a hopeful warning about the stability of your
4896 Cost is Ctrl+C wont kill children, but anyone
4897 who cares can have a go!
4899 dwProcessFlags
|= CREATE_NEW_CONSOLE
;
4903 /* Could be an else here to try cmd.exe / command.com in the path
4904 Now we'll just error out.. */
4906 PyErr_SetString(PyExc_RuntimeError
,
4907 "Cannot locate a COMSPEC environment variable to "
4908 "use as the shell");
4912 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
4913 siStartInfo
.cb
= sizeof(STARTUPINFO
);
4914 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
4915 siStartInfo
.hStdInput
= hStdin
;
4916 siStartInfo
.hStdOutput
= hStdout
;
4917 siStartInfo
.hStdError
= hStderr
;
4918 siStartInfo
.wShowWindow
= SW_HIDE
;
4920 if (CreateProcess(NULL
,
4930 /* Close the handles now so anyone waiting is woken. */
4931 CloseHandle(piProcInfo
.hThread
);
4933 /* Return process handle */
4934 *hProcess
= piProcInfo
.hProcess
;
4937 win32_error("CreateProcess", s2
);
4941 /* The following code is based off of KB: Q190351 */
4944 _PyPopen(char *cmdstring
, int mode
, int n
)
4946 HANDLE hChildStdinRd
, hChildStdinWr
, hChildStdoutRd
, hChildStdoutWr
,
4947 hChildStderrRd
, hChildStderrWr
, hChildStdinWrDup
, hChildStdoutRdDup
,
4948 hChildStderrRdDup
, hProcess
; /* hChildStdoutWrDup; */
4950 SECURITY_ATTRIBUTES saAttr
;
4957 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
4958 saAttr
.bInheritHandle
= TRUE
;
4959 saAttr
.lpSecurityDescriptor
= NULL
;
4961 if (!CreatePipe(&hChildStdinRd
, &hChildStdinWr
, &saAttr
, 0))
4962 return win32_error("CreatePipe", NULL
);
4964 /* Create new output read handle and the input write handle. Set
4965 * the inheritance properties to FALSE. Otherwise, the child inherits
4966 * these handles; resulting in non-closeable handles to the pipes
4968 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdinWr
,
4969 GetCurrentProcess(), &hChildStdinWrDup
, 0,
4971 DUPLICATE_SAME_ACCESS
);
4973 return win32_error("DuplicateHandle", NULL
);
4975 /* Close the inheritable version of ChildStdin
4976 that we're using. */
4977 CloseHandle(hChildStdinWr
);
4979 if (!CreatePipe(&hChildStdoutRd
, &hChildStdoutWr
, &saAttr
, 0))
4980 return win32_error("CreatePipe", NULL
);
4982 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdoutRd
,
4983 GetCurrentProcess(), &hChildStdoutRdDup
, 0,
4984 FALSE
, DUPLICATE_SAME_ACCESS
);
4986 return win32_error("DuplicateHandle", NULL
);
4988 /* Close the inheritable version of ChildStdout
4989 that we're using. */
4990 CloseHandle(hChildStdoutRd
);
4993 if (!CreatePipe(&hChildStderrRd
, &hChildStderrWr
, &saAttr
, 0))
4994 return win32_error("CreatePipe", NULL
);
4995 fSuccess
= DuplicateHandle(GetCurrentProcess(),
4997 GetCurrentProcess(),
4998 &hChildStderrRdDup
, 0,
4999 FALSE
, DUPLICATE_SAME_ACCESS
);
5001 return win32_error("DuplicateHandle", NULL
);
5002 /* Close the inheritable version of ChildStdErr that we're using. */
5003 CloseHandle(hChildStderrRd
);
5008 switch (mode
& (_O_RDONLY
| _O_TEXT
| _O_BINARY
| _O_WRONLY
)) {
5009 case _O_WRONLY
| _O_TEXT
:
5010 /* Case for writing to child Stdin in text mode. */
5011 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5012 f1
= _fdopen(fd1
, "w");
5013 f
= PyFile_FromFile(f1
, cmdstring
, "w", _PyPclose
);
5014 PyFile_SetBufSize(f
, 0);
5015 /* We don't care about these pipes anymore, so close them. */
5016 CloseHandle(hChildStdoutRdDup
);
5017 CloseHandle(hChildStderrRdDup
);
5020 case _O_RDONLY
| _O_TEXT
:
5021 /* Case for reading from child Stdout in text mode. */
5022 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5023 f1
= _fdopen(fd1
, "r");
5024 f
= PyFile_FromFile(f1
, cmdstring
, "r", _PyPclose
);
5025 PyFile_SetBufSize(f
, 0);
5026 /* We don't care about these pipes anymore, so close them. */
5027 CloseHandle(hChildStdinWrDup
);
5028 CloseHandle(hChildStderrRdDup
);
5031 case _O_RDONLY
| _O_BINARY
:
5032 /* Case for readinig from child Stdout in binary mode. */
5033 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5034 f1
= _fdopen(fd1
, "rb");
5035 f
= PyFile_FromFile(f1
, cmdstring
, "rb", _PyPclose
);
5036 PyFile_SetBufSize(f
, 0);
5037 /* We don't care about these pipes anymore, so close them. */
5038 CloseHandle(hChildStdinWrDup
);
5039 CloseHandle(hChildStderrRdDup
);
5042 case _O_WRONLY
| _O_BINARY
:
5043 /* Case for writing to child Stdin in binary mode. */
5044 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5045 f1
= _fdopen(fd1
, "wb");
5046 f
= PyFile_FromFile(f1
, cmdstring
, "wb", _PyPclose
);
5047 PyFile_SetBufSize(f
, 0);
5048 /* We don't care about these pipes anymore, so close them. */
5049 CloseHandle(hChildStdoutRdDup
);
5050 CloseHandle(hChildStderrRdDup
);
5062 if (mode
& _O_TEXT
) {
5070 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5071 f1
= _fdopen(fd1
, m2
);
5072 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5073 f2
= _fdopen(fd2
, m1
);
5074 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5075 PyFile_SetBufSize(p1
, 0);
5076 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5077 PyFile_SetBufSize(p2
, 0);
5080 CloseHandle(hChildStderrRdDup
);
5082 f
= PyTuple_Pack(2,p1
,p2
);
5092 PyObject
*p1
, *p2
, *p3
;
5094 if (mode
& _O_TEXT
) {
5102 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5103 f1
= _fdopen(fd1
, m2
);
5104 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5105 f2
= _fdopen(fd2
, m1
);
5106 fd3
= _open_osfhandle((Py_intptr_t
)hChildStderrRdDup
, mode
);
5107 f3
= _fdopen(fd3
, m1
);
5108 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5109 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5110 p3
= PyFile_FromFile(f3
, cmdstring
, m1
, _PyPclose
);
5111 PyFile_SetBufSize(p1
, 0);
5112 PyFile_SetBufSize(p2
, 0);
5113 PyFile_SetBufSize(p3
, 0);
5114 f
= PyTuple_Pack(3,p1
,p2
,p3
);
5124 if (!_PyPopenCreateProcess(cmdstring
,
5132 if (!_PyPopenCreateProcess(cmdstring
,
5141 * Insert the files we've created into the process dictionary
5142 * all referencing the list with the process handle and the
5143 * initial number of files (see description below in _PyPclose).
5144 * Since if _PyPclose later tried to wait on a process when all
5145 * handles weren't closed, it could create a deadlock with the
5146 * child, we spend some energy here to try to ensure that we
5147 * either insert all file handles into the dictionary or none
5148 * at all. It's a little clumsy with the various popen modes
5149 * and variable number of files involved.
5151 if (!_PyPopenProcs
) {
5152 _PyPopenProcs
= PyDict_New();
5155 if (_PyPopenProcs
) {
5156 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
[3];
5159 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
5160 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
5162 procObj
= PyList_New(2);
5163 hProcessObj
= PyLong_FromVoidPtr(hProcess
);
5164 intObj
= PyInt_FromLong(file_count
);
5166 if (procObj
&& hProcessObj
&& intObj
) {
5167 PyList_SetItem(procObj
,0,hProcessObj
);
5168 PyList_SetItem(procObj
,1,intObj
);
5170 fileObj
[0] = PyLong_FromVoidPtr(f1
);
5172 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
5176 if (file_count
>= 2) {
5177 fileObj
[1] = PyLong_FromVoidPtr(f2
);
5179 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
5184 if (file_count
>= 3) {
5185 fileObj
[2] = PyLong_FromVoidPtr(f3
);
5187 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
5193 if (ins_rc
[0] < 0 || !fileObj
[0] ||
5194 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
5195 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2])) {
5196 /* Something failed - remove any dictionary
5197 * entries that did make it.
5199 if (!ins_rc
[0] && fileObj
[0]) {
5200 PyDict_DelItem(_PyPopenProcs
,
5203 if (!ins_rc
[1] && fileObj
[1]) {
5204 PyDict_DelItem(_PyPopenProcs
,
5207 if (!ins_rc
[2] && fileObj
[2]) {
5208 PyDict_DelItem(_PyPopenProcs
,
5215 * Clean up our localized references for the dictionary keys
5216 * and value since PyDict_SetItem will Py_INCREF any copies
5217 * that got placed in the dictionary.
5219 Py_XDECREF(procObj
);
5220 Py_XDECREF(fileObj
[0]);
5221 Py_XDECREF(fileObj
[1]);
5222 Py_XDECREF(fileObj
[2]);
5225 /* Child is launched. Close the parents copy of those pipe
5226 * handles that only the child should have open. You need to
5227 * make sure that no handles to the write end of the output pipe
5228 * are maintained in this process or else the pipe will not close
5229 * when the child process exits and the ReadFile will hang. */
5231 if (!CloseHandle(hChildStdinRd
))
5232 return win32_error("CloseHandle", NULL
);
5234 if (!CloseHandle(hChildStdoutWr
))
5235 return win32_error("CloseHandle", NULL
);
5237 if ((n
!= 4) && (!CloseHandle(hChildStderrWr
)))
5238 return win32_error("CloseHandle", NULL
);
5244 * Wrapper for fclose() to use for popen* files, so we can retrieve the
5245 * exit code for the child process and return as a result of the close.
5247 * This function uses the _PyPopenProcs dictionary in order to map the
5248 * input file pointer to information about the process that was
5249 * originally created by the popen* call that created the file pointer.
5250 * The dictionary uses the file pointer as a key (with one entry
5251 * inserted for each file returned by the original popen* call) and a
5252 * single list object as the value for all files from a single call.
5253 * The list object contains the Win32 process handle at [0], and a file
5254 * count at [1], which is initialized to the total number of file
5255 * handles using that list.
5257 * This function closes whichever handle it is passed, and decrements
5258 * the file count in the dictionary for the process handle pointed to
5259 * by this file. On the last close (when the file count reaches zero),
5260 * this function will wait for the child process and then return its
5261 * exit code as the result of the close() operation. This permits the
5262 * files to be closed in any order - it is always the close() of the
5263 * final handle that will return the exit code.
5265 * NOTE: This function is currently called with the GIL released.
5266 * hence we use the GILState API to manage our state.
5269 static int _PyPclose(FILE *file
)
5274 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
;
5277 PyGILState_STATE state
;
5280 /* Close the file handle first, to ensure it can't block the
5281 * child from exiting if it's the last handle.
5283 result
= fclose(file
);
5285 state
= PyGILState_Ensure();
5287 if (_PyPopenProcs
) {
5288 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
5289 (procObj
= PyDict_GetItem(_PyPopenProcs
,
5290 fileObj
)) != NULL
&&
5291 (hProcessObj
= PyList_GetItem(procObj
,0)) != NULL
&&
5292 (intObj
= PyList_GetItem(procObj
,1)) != NULL
) {
5294 hProcess
= PyLong_AsVoidPtr(hProcessObj
);
5295 file_count
= PyInt_AsLong(intObj
);
5297 if (file_count
> 1) {
5298 /* Still other files referencing process */
5300 PyList_SetItem(procObj
,1,
5301 PyInt_FromLong(file_count
));
5303 /* Last file for this process */
5304 if (result
!= EOF
&&
5305 WaitForSingleObject(hProcess
, INFINITE
) != WAIT_FAILED
&&
5306 GetExitCodeProcess(hProcess
, &exit_code
)) {
5307 /* Possible truncation here in 16-bit environments, but
5308 * real exit codes are just the lower byte in any event.
5312 /* Indicate failure - this will cause the file object
5313 * to raise an I/O error and translate the last Win32
5314 * error code from errno. We do have a problem with
5315 * last errors that overlap the normal errno table,
5316 * but that's a consistent problem with the file object.
5318 if (result
!= EOF
) {
5319 /* If the error wasn't from the fclose(), then
5320 * set errno for the file object error handling.
5322 errno
= GetLastError();
5327 /* Free up the native handle at this point */
5328 CloseHandle(hProcess
);
5331 /* Remove this file pointer from dictionary */
5332 PyDict_DelItem(_PyPopenProcs
, fileObj
);
5334 if (PyDict_Size(_PyPopenProcs
) == 0) {
5335 Py_DECREF(_PyPopenProcs
);
5336 _PyPopenProcs
= NULL
;
5339 } /* if object retrieval ok */
5341 Py_XDECREF(fileObj
);
5342 } /* if _PyPopenProcs */
5345 PyGILState_Release(state
);
5350 #else /* which OS? */
5352 posix_popen(PyObject
*self
, PyObject
*args
)
5359 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
5361 /* Strip mode of binary or text modifiers */
5362 if (strcmp(mode
, "rb") == 0 || strcmp(mode
, "rt") == 0)
5364 else if (strcmp(mode
, "wb") == 0 || strcmp(mode
, "wt") == 0)
5366 Py_BEGIN_ALLOW_THREADS
5367 fp
= popen(name
, mode
);
5368 Py_END_ALLOW_THREADS
5370 return posix_error();
5371 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
5373 PyFile_SetBufSize(f
, bufsize
);
5377 #endif /* PYOS_??? */
5378 #endif /* HAVE_POPEN */
5382 PyDoc_STRVAR(posix_setuid__doc__
,
5384 Set the current process's user id.");
5387 posix_setuid(PyObject
*self
, PyObject
*args
)
5390 if (!PyArg_ParseTuple(args
, "i:setuid", &uid
))
5392 if (setuid(uid
) < 0)
5393 return posix_error();
5397 #endif /* HAVE_SETUID */
5401 PyDoc_STRVAR(posix_seteuid__doc__
,
5403 Set the current process's effective user id.");
5406 posix_seteuid (PyObject
*self
, PyObject
*args
)
5409 if (!PyArg_ParseTuple(args
, "i", &euid
)) {
5411 } else if (seteuid(euid
) < 0) {
5412 return posix_error();
5418 #endif /* HAVE_SETEUID */
5421 PyDoc_STRVAR(posix_setegid__doc__
,
5423 Set the current process's effective group id.");
5426 posix_setegid (PyObject
*self
, PyObject
*args
)
5429 if (!PyArg_ParseTuple(args
, "i", &egid
)) {
5431 } else if (setegid(egid
) < 0) {
5432 return posix_error();
5438 #endif /* HAVE_SETEGID */
5440 #ifdef HAVE_SETREUID
5441 PyDoc_STRVAR(posix_setreuid__doc__
,
5442 "setreuid(ruid, euid)\n\n\
5443 Set the current process's real and effective user ids.");
5446 posix_setreuid (PyObject
*self
, PyObject
*args
)
5449 if (!PyArg_ParseTuple(args
, "ii", &ruid
, &euid
)) {
5451 } else if (setreuid(ruid
, euid
) < 0) {
5452 return posix_error();
5458 #endif /* HAVE_SETREUID */
5460 #ifdef HAVE_SETREGID
5461 PyDoc_STRVAR(posix_setregid__doc__
,
5462 "setregid(rgid, egid)\n\n\
5463 Set the current process's real and effective group ids.");
5466 posix_setregid (PyObject
*self
, PyObject
*args
)
5469 if (!PyArg_ParseTuple(args
, "ii", &rgid
, &egid
)) {
5471 } else if (setregid(rgid
, egid
) < 0) {
5472 return posix_error();
5478 #endif /* HAVE_SETREGID */
5481 PyDoc_STRVAR(posix_setgid__doc__
,
5483 Set the current process's group id.");
5486 posix_setgid(PyObject
*self
, PyObject
*args
)
5489 if (!PyArg_ParseTuple(args
, "i:setgid", &gid
))
5491 if (setgid(gid
) < 0)
5492 return posix_error();
5496 #endif /* HAVE_SETGID */
5498 #ifdef HAVE_SETGROUPS
5499 PyDoc_STRVAR(posix_setgroups__doc__
,
5500 "setgroups(list)\n\n\
5501 Set the groups of the current process to list.");
5504 posix_setgroups(PyObject
*self
, PyObject
*groups
)
5507 gid_t grouplist
[MAX_GROUPS
];
5509 if (!PySequence_Check(groups
)) {
5510 PyErr_SetString(PyExc_TypeError
, "setgroups argument must be a sequence");
5513 len
= PySequence_Size(groups
);
5514 if (len
> MAX_GROUPS
) {
5515 PyErr_SetString(PyExc_ValueError
, "too many groups");
5518 for(i
= 0; i
< len
; i
++) {
5520 elem
= PySequence_GetItem(groups
, i
);
5523 if (!PyInt_Check(elem
)) {
5524 if (!PyLong_Check(elem
)) {
5525 PyErr_SetString(PyExc_TypeError
,
5526 "groups must be integers");
5530 unsigned long x
= PyLong_AsUnsignedLong(elem
);
5531 if (PyErr_Occurred()) {
5532 PyErr_SetString(PyExc_TypeError
,
5533 "group id too big");
5538 /* read back the value to see if it fitted in gid_t */
5539 if (grouplist
[i
] != x
) {
5540 PyErr_SetString(PyExc_TypeError
,
5541 "group id too big");
5547 long x
= PyInt_AsLong(elem
);
5549 if (grouplist
[i
] != x
) {
5550 PyErr_SetString(PyExc_TypeError
,
5551 "group id too big");
5559 if (setgroups(len
, grouplist
) < 0)
5560 return posix_error();
5564 #endif /* HAVE_SETGROUPS */
5566 #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
5568 wait_helper(int pid
, int status
, struct rusage
*ru
)
5571 static PyObject
*struct_rusage
;
5574 return posix_error();
5576 if (struct_rusage
== NULL
) {
5577 PyObject
*m
= PyImport_ImportModule("resource");
5580 struct_rusage
= PyObject_GetAttrString(m
, "struct_rusage");
5582 if (struct_rusage
== NULL
)
5586 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
5587 result
= PyStructSequence_New((PyTypeObject
*) struct_rusage
);
5592 #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
5595 PyStructSequence_SET_ITEM(result
, 0,
5596 PyFloat_FromDouble(doubletime(ru
->ru_utime
)));
5597 PyStructSequence_SET_ITEM(result
, 1,
5598 PyFloat_FromDouble(doubletime(ru
->ru_stime
)));
5599 #define SET_INT(result, index, value)\
5600 PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
5601 SET_INT(result
, 2, ru
->ru_maxrss
);
5602 SET_INT(result
, 3, ru
->ru_ixrss
);
5603 SET_INT(result
, 4, ru
->ru_idrss
);
5604 SET_INT(result
, 5, ru
->ru_isrss
);
5605 SET_INT(result
, 6, ru
->ru_minflt
);
5606 SET_INT(result
, 7, ru
->ru_majflt
);
5607 SET_INT(result
, 8, ru
->ru_nswap
);
5608 SET_INT(result
, 9, ru
->ru_inblock
);
5609 SET_INT(result
, 10, ru
->ru_oublock
);
5610 SET_INT(result
, 11, ru
->ru_msgsnd
);
5611 SET_INT(result
, 12, ru
->ru_msgrcv
);
5612 SET_INT(result
, 13, ru
->ru_nsignals
);
5613 SET_INT(result
, 14, ru
->ru_nvcsw
);
5614 SET_INT(result
, 15, ru
->ru_nivcsw
);
5617 if (PyErr_Occurred()) {
5622 return Py_BuildValue("iiN", pid
, status
, result
);
5624 #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
5627 PyDoc_STRVAR(posix_wait3__doc__
,
5628 "wait3(options) -> (pid, status, rusage)\n\n\
5629 Wait for completion of a child process.");
5632 posix_wait3(PyObject
*self
, PyObject
*args
)
5637 WAIT_STATUS_INT(status
) = 0;
5639 if (!PyArg_ParseTuple(args
, "i:wait3", &options
))
5642 Py_BEGIN_ALLOW_THREADS
5643 pid
= wait3(&status
, options
, &ru
);
5644 Py_END_ALLOW_THREADS
5646 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5648 #endif /* HAVE_WAIT3 */
5651 PyDoc_STRVAR(posix_wait4__doc__
,
5652 "wait4(pid, options) -> (pid, status, rusage)\n\n\
5653 Wait for completion of a given child process.");
5656 posix_wait4(PyObject
*self
, PyObject
*args
)
5661 WAIT_STATUS_INT(status
) = 0;
5663 if (!PyArg_ParseTuple(args
, "ii:wait4", &pid
, &options
))
5666 Py_BEGIN_ALLOW_THREADS
5667 pid
= wait4(pid
, &status
, options
, &ru
);
5668 Py_END_ALLOW_THREADS
5670 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5672 #endif /* HAVE_WAIT4 */
5675 PyDoc_STRVAR(posix_waitpid__doc__
,
5676 "waitpid(pid, options) -> (pid, status)\n\n\
5677 Wait for completion of a given child process.");
5680 posix_waitpid(PyObject
*self
, PyObject
*args
)
5684 WAIT_STATUS_INT(status
) = 0;
5686 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5688 Py_BEGIN_ALLOW_THREADS
5689 pid
= waitpid(pid
, &status
, options
);
5690 Py_END_ALLOW_THREADS
5692 return posix_error();
5694 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5697 #elif defined(HAVE_CWAIT)
5699 /* MS C has a variant of waitpid() that's usable for most purposes. */
5700 PyDoc_STRVAR(posix_waitpid__doc__
,
5701 "waitpid(pid, options) -> (pid, status << 8)\n\n"
5702 "Wait for completion of a given process. options is ignored on Windows.");
5705 posix_waitpid(PyObject
*self
, PyObject
*args
)
5708 int status
, options
;
5710 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5712 Py_BEGIN_ALLOW_THREADS
5713 pid
= _cwait(&status
, pid
, options
);
5714 Py_END_ALLOW_THREADS
5716 return posix_error();
5718 /* shift the status left a byte so this is more like the POSIX waitpid */
5719 return Py_BuildValue("ii", pid
, status
<< 8);
5721 #endif /* HAVE_WAITPID || HAVE_CWAIT */
5724 PyDoc_STRVAR(posix_wait__doc__
,
5725 "wait() -> (pid, status)\n\n\
5726 Wait for completion of a child process.");
5729 posix_wait(PyObject
*self
, PyObject
*noargs
)
5733 WAIT_STATUS_INT(status
) = 0;
5735 Py_BEGIN_ALLOW_THREADS
5736 pid
= wait(&status
);
5737 Py_END_ALLOW_THREADS
5739 return posix_error();
5741 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5746 PyDoc_STRVAR(posix_lstat__doc__
,
5747 "lstat(path) -> stat result\n\n\
5748 Like stat(path), but do not follow symbolic links.");
5751 posix_lstat(PyObject
*self
, PyObject
*args
)
5754 return posix_do_stat(self
, args
, "et:lstat", lstat
, NULL
, NULL
);
5755 #else /* !HAVE_LSTAT */
5757 return posix_do_stat(self
, args
, "et:lstat", STAT
, "U:lstat", win32_wstat
);
5759 return posix_do_stat(self
, args
, "et:lstat", STAT
, NULL
, NULL
);
5761 #endif /* !HAVE_LSTAT */
5765 #ifdef HAVE_READLINK
5766 PyDoc_STRVAR(posix_readlink__doc__
,
5767 "readlink(path) -> path\n\n\
5768 Return a string representing the path to which the symbolic link points.");
5771 posix_readlink(PyObject
*self
, PyObject
*args
)
5774 char buf
[MAXPATHLEN
];
5777 #ifdef Py_USING_UNICODE
5778 int arg_is_unicode
= 0;
5781 if (!PyArg_ParseTuple(args
, "et:readlink",
5782 Py_FileSystemDefaultEncoding
, &path
))
5784 #ifdef Py_USING_UNICODE
5785 v
= PySequence_GetItem(args
, 0);
5786 if (v
== NULL
) return NULL
;
5788 if (PyUnicode_Check(v
)) {
5794 Py_BEGIN_ALLOW_THREADS
5795 n
= readlink(path
, buf
, (int) sizeof buf
);
5796 Py_END_ALLOW_THREADS
5798 return posix_error_with_filename(path
);
5800 v
= PyString_FromStringAndSize(buf
, n
);
5801 #ifdef Py_USING_UNICODE
5802 if (arg_is_unicode
) {
5805 w
= PyUnicode_FromEncodedObject(v
,
5806 Py_FileSystemDefaultEncoding
,
5813 /* fall back to the original byte string, as
5814 discussed in patch #683592 */
5821 #endif /* HAVE_READLINK */
5825 PyDoc_STRVAR(posix_symlink__doc__
,
5826 "symlink(src, dst)\n\n\
5827 Create a symbolic link pointing to src named dst.");
5830 posix_symlink(PyObject
*self
, PyObject
*args
)
5832 return posix_2str(args
, "etet:symlink", symlink
);
5834 #endif /* HAVE_SYMLINK */
5839 #define HZ 60 /* Universal constant :-) */
5842 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
5848 Py_BEGIN_ALLOW_THREADS
5849 DosQuerySysInfo(QSV_MS_COUNT
, QSV_MS_COUNT
, &value
, sizeof(value
));
5850 Py_END_ALLOW_THREADS
5856 posix_times(PyObject
*self
, PyObject
*noargs
)
5858 /* Currently Only Uptime is Provided -- Others Later */
5859 return Py_BuildValue("ddddd",
5860 (double)0 /* t.tms_utime / HZ */,
5861 (double)0 /* t.tms_stime / HZ */,
5862 (double)0 /* t.tms_cutime / HZ */,
5863 (double)0 /* t.tms_cstime / HZ */,
5864 (double)system_uptime() / 1000);
5868 posix_times(PyObject
*self
, PyObject
*noargs
)
5874 if (c
== (clock_t) -1)
5875 return posix_error();
5876 return Py_BuildValue("ddddd",
5877 (double)t
.tms_utime
/ HZ
,
5878 (double)t
.tms_stime
/ HZ
,
5879 (double)t
.tms_cutime
/ HZ
,
5880 (double)t
.tms_cstime
/ HZ
,
5883 #endif /* not OS2 */
5884 #endif /* HAVE_TIMES */
5888 #define HAVE_TIMES /* so the method table will pick it up */
5890 posix_times(PyObject
*self
, PyObject
*noargs
)
5892 FILETIME create
, exit
, kernel
, user
;
5894 hProc
= GetCurrentProcess();
5895 GetProcessTimes(hProc
, &create
, &exit
, &kernel
, &user
);
5896 /* The fields of a FILETIME structure are the hi and lo part
5897 of a 64-bit value expressed in 100 nanosecond units.
5898 1e7 is one second in such units; 1e-7 the inverse.
5899 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
5901 return Py_BuildValue(
5903 (double)(kernel
.dwHighDateTime
*429.4967296 +
5904 kernel
.dwLowDateTime
*1e-7),
5905 (double)(user
.dwHighDateTime
*429.4967296 +
5906 user
.dwLowDateTime
*1e-7),
5911 #endif /* MS_WINDOWS */
5914 PyDoc_STRVAR(posix_times__doc__
,
5915 "times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\
5916 Return a tuple of floating point numbers indicating process times.");
5921 PyDoc_STRVAR(posix_getsid__doc__
,
5922 "getsid(pid) -> sid\n\n\
5923 Call the system call getsid().");
5926 posix_getsid(PyObject
*self
, PyObject
*args
)
5929 if (!PyArg_ParseTuple(args
, "i:getsid", &pid
))
5933 return posix_error();
5934 return PyInt_FromLong((long)sid
);
5936 #endif /* HAVE_GETSID */
5940 PyDoc_STRVAR(posix_setsid__doc__
,
5942 Call the system call setsid().");
5945 posix_setsid(PyObject
*self
, PyObject
*noargs
)
5948 return posix_error();
5952 #endif /* HAVE_SETSID */
5955 PyDoc_STRVAR(posix_setpgid__doc__
,
5956 "setpgid(pid, pgrp)\n\n\
5957 Call the system call setpgid().");
5960 posix_setpgid(PyObject
*self
, PyObject
*args
)
5963 if (!PyArg_ParseTuple(args
, "ii:setpgid", &pid
, &pgrp
))
5965 if (setpgid(pid
, pgrp
) < 0)
5966 return posix_error();
5970 #endif /* HAVE_SETPGID */
5973 #ifdef HAVE_TCGETPGRP
5974 PyDoc_STRVAR(posix_tcgetpgrp__doc__
,
5975 "tcgetpgrp(fd) -> pgid\n\n\
5976 Return the process group associated with the terminal given by a fd.");
5979 posix_tcgetpgrp(PyObject
*self
, PyObject
*args
)
5982 if (!PyArg_ParseTuple(args
, "i:tcgetpgrp", &fd
))
5984 pgid
= tcgetpgrp(fd
);
5986 return posix_error();
5987 return PyInt_FromLong((long)pgid
);
5989 #endif /* HAVE_TCGETPGRP */
5992 #ifdef HAVE_TCSETPGRP
5993 PyDoc_STRVAR(posix_tcsetpgrp__doc__
,
5994 "tcsetpgrp(fd, pgid)\n\n\
5995 Set the process group associated with the terminal given by a fd.");
5998 posix_tcsetpgrp(PyObject
*self
, PyObject
*args
)
6001 if (!PyArg_ParseTuple(args
, "ii:tcsetpgrp", &fd
, &pgid
))
6003 if (tcsetpgrp(fd
, pgid
) < 0)
6004 return posix_error();
6008 #endif /* HAVE_TCSETPGRP */
6010 /* Functions acting on file descriptors */
6012 PyDoc_STRVAR(posix_open__doc__
,
6013 "open(filename, flag [, mode=0777]) -> fd\n\n\
6014 Open a file (for low level IO).");
6017 posix_open(PyObject
*self
, PyObject
*args
)
6025 if (unicode_file_names()) {
6026 PyUnicodeObject
*po
;
6027 if (PyArg_ParseTuple(args
, "Ui|i:mkdir", &po
, &flag
, &mode
)) {
6028 Py_BEGIN_ALLOW_THREADS
6029 /* PyUnicode_AS_UNICODE OK without thread
6030 lock as it is a simple dereference. */
6031 fd
= _wopen(PyUnicode_AS_UNICODE(po
), flag
, mode
);
6032 Py_END_ALLOW_THREADS
6034 return posix_error();
6035 return PyInt_FromLong((long)fd
);
6037 /* Drop the argument parsing error as narrow strings
6043 if (!PyArg_ParseTuple(args
, "eti|i",
6044 Py_FileSystemDefaultEncoding
, &file
,
6048 Py_BEGIN_ALLOW_THREADS
6049 fd
= open(file
, flag
, mode
);
6050 Py_END_ALLOW_THREADS
6052 return posix_error_with_allocated_filename(file
);
6054 return PyInt_FromLong((long)fd
);
6058 PyDoc_STRVAR(posix_close__doc__
,
6060 Close a file descriptor (for low level IO).");
6063 posix_close(PyObject
*self
, PyObject
*args
)
6066 if (!PyArg_ParseTuple(args
, "i:close", &fd
))
6068 Py_BEGIN_ALLOW_THREADS
6070 Py_END_ALLOW_THREADS
6072 return posix_error();
6078 PyDoc_STRVAR(posix_dup__doc__
,
6079 "dup(fd) -> fd2\n\n\
6080 Return a duplicate of a file descriptor.");
6083 posix_dup(PyObject
*self
, PyObject
*args
)
6086 if (!PyArg_ParseTuple(args
, "i:dup", &fd
))
6088 Py_BEGIN_ALLOW_THREADS
6090 Py_END_ALLOW_THREADS
6092 return posix_error();
6093 return PyInt_FromLong((long)fd
);
6097 PyDoc_STRVAR(posix_dup2__doc__
,
6098 "dup2(old_fd, new_fd)\n\n\
6099 Duplicate file descriptor.");
6102 posix_dup2(PyObject
*self
, PyObject
*args
)
6105 if (!PyArg_ParseTuple(args
, "ii:dup2", &fd
, &fd2
))
6107 Py_BEGIN_ALLOW_THREADS
6108 res
= dup2(fd
, fd2
);
6109 Py_END_ALLOW_THREADS
6111 return posix_error();
6117 PyDoc_STRVAR(posix_lseek__doc__
,
6118 "lseek(fd, pos, how) -> newpos\n\n\
6119 Set the current position of a file descriptor.");
6122 posix_lseek(PyObject
*self
, PyObject
*args
)
6125 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6126 PY_LONG_LONG pos
, res
;
6131 if (!PyArg_ParseTuple(args
, "iOi:lseek", &fd
, &posobj
, &how
))
6134 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
6136 case 0: how
= SEEK_SET
; break;
6137 case 1: how
= SEEK_CUR
; break;
6138 case 2: how
= SEEK_END
; break;
6140 #endif /* SEEK_END */
6142 #if !defined(HAVE_LARGEFILE_SUPPORT)
6143 pos
= PyInt_AsLong(posobj
);
6145 pos
= PyLong_Check(posobj
) ?
6146 PyLong_AsLongLong(posobj
) : PyInt_AsLong(posobj
);
6148 if (PyErr_Occurred())
6151 Py_BEGIN_ALLOW_THREADS
6152 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6153 res
= _lseeki64(fd
, pos
, how
);
6155 res
= lseek(fd
, pos
, how
);
6157 Py_END_ALLOW_THREADS
6159 return posix_error();
6161 #if !defined(HAVE_LARGEFILE_SUPPORT)
6162 return PyInt_FromLong(res
);
6164 return PyLong_FromLongLong(res
);
6169 PyDoc_STRVAR(posix_read__doc__
,
6170 "read(fd, buffersize) -> string\n\n\
6171 Read a file descriptor.");
6174 posix_read(PyObject
*self
, PyObject
*args
)
6178 if (!PyArg_ParseTuple(args
, "ii:read", &fd
, &size
))
6182 return posix_error();
6184 buffer
= PyString_FromStringAndSize((char *)NULL
, size
);
6187 Py_BEGIN_ALLOW_THREADS
6188 n
= read(fd
, PyString_AsString(buffer
), size
);
6189 Py_END_ALLOW_THREADS
6192 return posix_error();
6195 _PyString_Resize(&buffer
, n
);
6200 PyDoc_STRVAR(posix_write__doc__
,
6201 "write(fd, string) -> byteswritten\n\n\
6202 Write a string to a file descriptor.");
6205 posix_write(PyObject
*self
, PyObject
*args
)
6211 if (!PyArg_ParseTuple(args
, "is#:write", &fd
, &buffer
, &size
))
6213 Py_BEGIN_ALLOW_THREADS
6214 size
= write(fd
, buffer
, (size_t)size
);
6215 Py_END_ALLOW_THREADS
6217 return posix_error();
6218 return PyInt_FromSsize_t(size
);
6222 PyDoc_STRVAR(posix_fstat__doc__
,
6223 "fstat(fd) -> stat result\n\n\
6224 Like stat(), but for an open file descriptor.");
6227 posix_fstat(PyObject
*self
, PyObject
*args
)
6232 if (!PyArg_ParseTuple(args
, "i:fstat", &fd
))
6235 /* on OpenVMS we must ensure that all bytes are written to the file */
6238 Py_BEGIN_ALLOW_THREADS
6239 res
= FSTAT(fd
, &st
);
6240 Py_END_ALLOW_THREADS
6243 return win32_error("fstat", NULL
);
6245 return posix_error();
6249 return _pystat_fromstructstat(&st
);
6253 PyDoc_STRVAR(posix_fdopen__doc__
,
6254 "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\
6255 Return an open file object connected to a file descriptor.");
6258 posix_fdopen(PyObject
*self
, PyObject
*args
)
6261 char *orgmode
= "r";
6266 if (!PyArg_ParseTuple(args
, "i|si", &fd
, &orgmode
, &bufsize
))
6269 /* Sanitize mode. See fileobject.c */
6270 mode
= PyMem_MALLOC(strlen(orgmode
)+3);
6275 strcpy(mode
, orgmode
);
6276 if (_PyFile_SanitizeMode(mode
)) {
6280 Py_BEGIN_ALLOW_THREADS
6281 #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
6282 if (mode
[0] == 'a') {
6283 /* try to make sure the O_APPEND flag is set */
6285 flags
= fcntl(fd
, F_GETFL
);
6287 fcntl(fd
, F_SETFL
, flags
| O_APPEND
);
6288 fp
= fdopen(fd
, mode
);
6289 if (fp
== NULL
&& flags
!= -1)
6290 /* restore old mode if fdopen failed */
6291 fcntl(fd
, F_SETFL
, flags
);
6293 fp
= fdopen(fd
, mode
);
6296 fp
= fdopen(fd
, mode
);
6298 Py_END_ALLOW_THREADS
6301 return posix_error();
6302 f
= PyFile_FromFile(fp
, "<fdopen>", orgmode
, fclose
);
6304 PyFile_SetBufSize(f
, bufsize
);
6308 PyDoc_STRVAR(posix_isatty__doc__
,
6309 "isatty(fd) -> bool\n\n\
6310 Return True if the file descriptor 'fd' is an open file descriptor\n\
6311 connected to the slave end of a terminal.");
6314 posix_isatty(PyObject
*self
, PyObject
*args
)
6317 if (!PyArg_ParseTuple(args
, "i:isatty", &fd
))
6319 return PyBool_FromLong(isatty(fd
));
6323 PyDoc_STRVAR(posix_pipe__doc__
,
6324 "pipe() -> (read_end, write_end)\n\n\
6328 posix_pipe(PyObject
*self
, PyObject
*noargs
)
6330 #if defined(PYOS_OS2)
6334 Py_BEGIN_ALLOW_THREADS
6335 rc
= DosCreatePipe( &read
, &write
, 4096);
6336 Py_END_ALLOW_THREADS
6338 return os2_error(rc
);
6340 return Py_BuildValue("(ii)", read
, write
);
6342 #if !defined(MS_WINDOWS)
6345 Py_BEGIN_ALLOW_THREADS
6347 Py_END_ALLOW_THREADS
6349 return posix_error();
6350 return Py_BuildValue("(ii)", fds
[0], fds
[1]);
6351 #else /* MS_WINDOWS */
6353 int read_fd
, write_fd
;
6355 Py_BEGIN_ALLOW_THREADS
6356 ok
= CreatePipe(&read
, &write
, NULL
, 0);
6357 Py_END_ALLOW_THREADS
6359 return win32_error("CreatePipe", NULL
);
6360 read_fd
= _open_osfhandle((Py_intptr_t
)read
, 0);
6361 write_fd
= _open_osfhandle((Py_intptr_t
)write
, 1);
6362 return Py_BuildValue("(ii)", read_fd
, write_fd
);
6363 #endif /* MS_WINDOWS */
6366 #endif /* HAVE_PIPE */
6370 PyDoc_STRVAR(posix_mkfifo__doc__
,
6371 "mkfifo(filename [, mode=0666])\n\n\
6372 Create a FIFO (a POSIX named pipe).");
6375 posix_mkfifo(PyObject
*self
, PyObject
*args
)
6380 if (!PyArg_ParseTuple(args
, "s|i:mkfifo", &filename
, &mode
))
6382 Py_BEGIN_ALLOW_THREADS
6383 res
= mkfifo(filename
, mode
);
6384 Py_END_ALLOW_THREADS
6386 return posix_error();
6393 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
6394 PyDoc_STRVAR(posix_mknod__doc__
,
6395 "mknod(filename [, mode=0600, device])\n\n\
6396 Create a filesystem node (file, device special file or named pipe)\n\
6397 named filename. mode specifies both the permissions to use and the\n\
6398 type of node to be created, being combined (bitwise OR) with one of\n\
6399 S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\
6400 device defines the newly created device special file (probably using\n\
6401 os.makedev()), otherwise it is ignored.");
6405 posix_mknod(PyObject
*self
, PyObject
*args
)
6411 if (!PyArg_ParseTuple(args
, "s|ii:mknod", &filename
, &mode
, &device
))
6413 Py_BEGIN_ALLOW_THREADS
6414 res
= mknod(filename
, mode
, device
);
6415 Py_END_ALLOW_THREADS
6417 return posix_error();
6423 #ifdef HAVE_DEVICE_MACROS
6424 PyDoc_STRVAR(posix_major__doc__
,
6425 "major(device) -> major number\n\
6426 Extracts a device major number from a raw device number.");
6429 posix_major(PyObject
*self
, PyObject
*args
)
6432 if (!PyArg_ParseTuple(args
, "i:major", &device
))
6434 return PyInt_FromLong((long)major(device
));
6437 PyDoc_STRVAR(posix_minor__doc__
,
6438 "minor(device) -> minor number\n\
6439 Extracts a device minor number from a raw device number.");
6442 posix_minor(PyObject
*self
, PyObject
*args
)
6445 if (!PyArg_ParseTuple(args
, "i:minor", &device
))
6447 return PyInt_FromLong((long)minor(device
));
6450 PyDoc_STRVAR(posix_makedev__doc__
,
6451 "makedev(major, minor) -> device number\n\
6452 Composes a raw device number from the major and minor device numbers.");
6455 posix_makedev(PyObject
*self
, PyObject
*args
)
6458 if (!PyArg_ParseTuple(args
, "ii:makedev", &major
, &minor
))
6460 return PyInt_FromLong((long)makedev(major
, minor
));
6462 #endif /* device macros */
6465 #ifdef HAVE_FTRUNCATE
6466 PyDoc_STRVAR(posix_ftruncate__doc__
,
6467 "ftruncate(fd, length)\n\n\
6468 Truncate a file to a specified length.");
6471 posix_ftruncate(PyObject
*self
, PyObject
*args
)
6478 if (!PyArg_ParseTuple(args
, "iO:ftruncate", &fd
, &lenobj
))
6481 #if !defined(HAVE_LARGEFILE_SUPPORT)
6482 length
= PyInt_AsLong(lenobj
);
6484 length
= PyLong_Check(lenobj
) ?
6485 PyLong_AsLongLong(lenobj
) : PyInt_AsLong(lenobj
);
6487 if (PyErr_Occurred())
6490 Py_BEGIN_ALLOW_THREADS
6491 res
= ftruncate(fd
, length
);
6492 Py_END_ALLOW_THREADS
6494 PyErr_SetFromErrno(PyExc_IOError
);
6503 PyDoc_STRVAR(posix_putenv__doc__
,
6504 "putenv(key, value)\n\n\
6505 Change or add an environment variable.");
6507 /* Save putenv() parameters as values here, so we can collect them when they
6508 * get re-set with another call for the same key. */
6509 static PyObject
*posix_putenv_garbage
;
6512 posix_putenv(PyObject
*self
, PyObject
*args
)
6519 if (!PyArg_ParseTuple(args
, "ss:putenv", &s1
, &s2
))
6522 #if defined(PYOS_OS2)
6523 if (stricmp(s1
, "BEGINLIBPATH") == 0) {
6526 rc
= DosSetExtLIBPATH(s2
, BEGIN_LIBPATH
);
6528 return os2_error(rc
);
6530 } else if (stricmp(s1
, "ENDLIBPATH") == 0) {
6533 rc
= DosSetExtLIBPATH(s2
, END_LIBPATH
);
6535 return os2_error(rc
);
6539 /* XXX This can leak memory -- not easy to fix :-( */
6540 len
= strlen(s1
) + strlen(s2
) + 2;
6541 /* len includes space for a trailing \0; the size arg to
6542 PyString_FromStringAndSize does not count that */
6543 newstr
= PyString_FromStringAndSize(NULL
, (int)len
- 1);
6545 return PyErr_NoMemory();
6546 newenv
= PyString_AS_STRING(newstr
);
6547 PyOS_snprintf(newenv
, len
, "%s=%s", s1
, s2
);
6548 if (putenv(newenv
)) {
6553 /* Install the first arg and newstr in posix_putenv_garbage;
6554 * this will cause previous value to be collected. This has to
6555 * happen after the real putenv() call because the old value
6556 * was still accessible until then. */
6557 if (PyDict_SetItem(posix_putenv_garbage
,
6558 PyTuple_GET_ITEM(args
, 0), newstr
)) {
6559 /* really not much we can do; just leak */
6566 #if defined(PYOS_OS2)
6574 #ifdef HAVE_UNSETENV
6575 PyDoc_STRVAR(posix_unsetenv__doc__
,
6577 Delete an environment variable.");
6580 posix_unsetenv(PyObject
*self
, PyObject
*args
)
6584 if (!PyArg_ParseTuple(args
, "s:unsetenv", &s1
))
6589 /* Remove the key from posix_putenv_garbage;
6590 * this will cause it to be collected. This has to
6591 * happen after the real unsetenv() call because the
6592 * old value was still accessible until then.
6594 if (PyDict_DelItem(posix_putenv_garbage
,
6595 PyTuple_GET_ITEM(args
, 0))) {
6596 /* really not much we can do; just leak */
6603 #endif /* unsetenv */
6605 #ifdef HAVE_STRERROR
6606 PyDoc_STRVAR(posix_strerror__doc__
,
6607 "strerror(code) -> string\n\n\
6608 Translate an error code to a message string.");
6611 posix_strerror(PyObject
*self
, PyObject
*args
)
6615 if (!PyArg_ParseTuple(args
, "i:strerror", &code
))
6617 message
= strerror(code
);
6618 if (message
== NULL
) {
6619 PyErr_SetString(PyExc_ValueError
,
6620 "strerror() argument out of range");
6623 return PyString_FromString(message
);
6625 #endif /* strerror */
6628 #ifdef HAVE_SYS_WAIT_H
6631 PyDoc_STRVAR(posix_WCOREDUMP__doc__
,
6632 "WCOREDUMP(status) -> bool\n\n\
6633 Return True if the process returning 'status' was dumped to a core file.");
6636 posix_WCOREDUMP(PyObject
*self
, PyObject
*args
)
6639 WAIT_STATUS_INT(status
) = 0;
6641 if (!PyArg_ParseTuple(args
, "i:WCOREDUMP", &WAIT_STATUS_INT(status
)))
6644 return PyBool_FromLong(WCOREDUMP(status
));
6646 #endif /* WCOREDUMP */
6649 PyDoc_STRVAR(posix_WIFCONTINUED__doc__
,
6650 "WIFCONTINUED(status) -> bool\n\n\
6651 Return True if the process returning 'status' was continued from a\n\
6652 job control stop.");
6655 posix_WIFCONTINUED(PyObject
*self
, PyObject
*args
)
6658 WAIT_STATUS_INT(status
) = 0;
6660 if (!PyArg_ParseTuple(args
, "i:WCONTINUED", &WAIT_STATUS_INT(status
)))
6663 return PyBool_FromLong(WIFCONTINUED(status
));
6665 #endif /* WIFCONTINUED */
6668 PyDoc_STRVAR(posix_WIFSTOPPED__doc__
,
6669 "WIFSTOPPED(status) -> bool\n\n\
6670 Return True if the process returning 'status' was stopped.");
6673 posix_WIFSTOPPED(PyObject
*self
, PyObject
*args
)
6676 WAIT_STATUS_INT(status
) = 0;
6678 if (!PyArg_ParseTuple(args
, "i:WIFSTOPPED", &WAIT_STATUS_INT(status
)))
6681 return PyBool_FromLong(WIFSTOPPED(status
));
6683 #endif /* WIFSTOPPED */
6686 PyDoc_STRVAR(posix_WIFSIGNALED__doc__
,
6687 "WIFSIGNALED(status) -> bool\n\n\
6688 Return True if the process returning 'status' was terminated by a signal.");
6691 posix_WIFSIGNALED(PyObject
*self
, PyObject
*args
)
6694 WAIT_STATUS_INT(status
) = 0;
6696 if (!PyArg_ParseTuple(args
, "i:WIFSIGNALED", &WAIT_STATUS_INT(status
)))
6699 return PyBool_FromLong(WIFSIGNALED(status
));
6701 #endif /* WIFSIGNALED */
6704 PyDoc_STRVAR(posix_WIFEXITED__doc__
,
6705 "WIFEXITED(status) -> bool\n\n\
6706 Return true if the process returning 'status' exited using the exit()\n\
6710 posix_WIFEXITED(PyObject
*self
, PyObject
*args
)
6713 WAIT_STATUS_INT(status
) = 0;
6715 if (!PyArg_ParseTuple(args
, "i:WIFEXITED", &WAIT_STATUS_INT(status
)))
6718 return PyBool_FromLong(WIFEXITED(status
));
6720 #endif /* WIFEXITED */
6723 PyDoc_STRVAR(posix_WEXITSTATUS__doc__
,
6724 "WEXITSTATUS(status) -> integer\n\n\
6725 Return the process return code from 'status'.");
6728 posix_WEXITSTATUS(PyObject
*self
, PyObject
*args
)
6731 WAIT_STATUS_INT(status
) = 0;
6733 if (!PyArg_ParseTuple(args
, "i:WEXITSTATUS", &WAIT_STATUS_INT(status
)))
6736 return Py_BuildValue("i", WEXITSTATUS(status
));
6738 #endif /* WEXITSTATUS */
6741 PyDoc_STRVAR(posix_WTERMSIG__doc__
,
6742 "WTERMSIG(status) -> integer\n\n\
6743 Return the signal that terminated the process that provided the 'status'\n\
6747 posix_WTERMSIG(PyObject
*self
, PyObject
*args
)
6750 WAIT_STATUS_INT(status
) = 0;
6752 if (!PyArg_ParseTuple(args
, "i:WTERMSIG", &WAIT_STATUS_INT(status
)))
6755 return Py_BuildValue("i", WTERMSIG(status
));
6757 #endif /* WTERMSIG */
6760 PyDoc_STRVAR(posix_WSTOPSIG__doc__
,
6761 "WSTOPSIG(status) -> integer\n\n\
6762 Return the signal that stopped the process that provided\n\
6763 the 'status' value.");
6766 posix_WSTOPSIG(PyObject
*self
, PyObject
*args
)
6769 WAIT_STATUS_INT(status
) = 0;
6771 if (!PyArg_ParseTuple(args
, "i:WSTOPSIG", &WAIT_STATUS_INT(status
)))
6774 return Py_BuildValue("i", WSTOPSIG(status
));
6776 #endif /* WSTOPSIG */
6778 #endif /* HAVE_SYS_WAIT_H */
6781 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
6783 /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
6784 needed definitions in sys/statvfs.h */
6787 #include <sys/statvfs.h>
6790 _pystatvfs_fromstructstatvfs(struct statvfs st
) {
6791 PyObject
*v
= PyStructSequence_New(&StatVFSResultType
);
6795 #if !defined(HAVE_LARGEFILE_SUPPORT)
6796 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6797 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6798 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long) st
.f_blocks
));
6799 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long) st
.f_bfree
));
6800 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long) st
.f_bavail
));
6801 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long) st
.f_files
));
6802 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong((long) st
.f_ffree
));
6803 PyStructSequence_SET_ITEM(v
, 7, PyInt_FromLong((long) st
.f_favail
));
6804 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6805 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6807 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6808 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6809 PyStructSequence_SET_ITEM(v
, 2,
6810 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_blocks
));
6811 PyStructSequence_SET_ITEM(v
, 3,
6812 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bfree
));
6813 PyStructSequence_SET_ITEM(v
, 4,
6814 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bavail
));
6815 PyStructSequence_SET_ITEM(v
, 5,
6816 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_files
));
6817 PyStructSequence_SET_ITEM(v
, 6,
6818 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_ffree
));
6819 PyStructSequence_SET_ITEM(v
, 7,
6820 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_favail
));
6821 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6822 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6828 PyDoc_STRVAR(posix_fstatvfs__doc__
,
6829 "fstatvfs(fd) -> statvfs result\n\n\
6830 Perform an fstatvfs system call on the given fd.");
6833 posix_fstatvfs(PyObject
*self
, PyObject
*args
)
6838 if (!PyArg_ParseTuple(args
, "i:fstatvfs", &fd
))
6840 Py_BEGIN_ALLOW_THREADS
6841 res
= fstatvfs(fd
, &st
);
6842 Py_END_ALLOW_THREADS
6844 return posix_error();
6846 return _pystatvfs_fromstructstatvfs(st
);
6848 #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
6851 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
6852 #include <sys/statvfs.h>
6854 PyDoc_STRVAR(posix_statvfs__doc__
,
6855 "statvfs(path) -> statvfs result\n\n\
6856 Perform a statvfs system call on the given path.");
6859 posix_statvfs(PyObject
*self
, PyObject
*args
)
6864 if (!PyArg_ParseTuple(args
, "s:statvfs", &path
))
6866 Py_BEGIN_ALLOW_THREADS
6867 res
= statvfs(path
, &st
);
6868 Py_END_ALLOW_THREADS
6870 return posix_error_with_filename(path
);
6872 return _pystatvfs_fromstructstatvfs(st
);
6874 #endif /* HAVE_STATVFS */
6878 PyDoc_STRVAR(posix_tempnam__doc__
,
6879 "tempnam([dir[, prefix]]) -> string\n\n\
6880 Return a unique name for a temporary file.\n\
6881 The directory and a prefix may be specified as strings; they may be omitted\n\
6882 or None if not needed.");
6885 posix_tempnam(PyObject
*self
, PyObject
*args
)
6887 PyObject
*result
= NULL
;
6892 if (!PyArg_ParseTuple(args
, "|zz:tempnam", &dir
, &pfx
))
6895 if (PyErr_Warn(PyExc_RuntimeWarning
,
6896 "tempnam is a potential security risk to your program") < 0)
6900 name
= _tempnam(dir
, pfx
);
6902 name
= tempnam(dir
, pfx
);
6905 return PyErr_NoMemory();
6906 result
= PyString_FromString(name
);
6914 PyDoc_STRVAR(posix_tmpfile__doc__
,
6915 "tmpfile() -> file object\n\n\
6916 Create a temporary file with no directory entries.");
6919 posix_tmpfile(PyObject
*self
, PyObject
*noargs
)
6925 return posix_error();
6926 return PyFile_FromFile(fp
, "<tmpfile>", "w+b", fclose
);
6932 PyDoc_STRVAR(posix_tmpnam__doc__
,
6933 "tmpnam() -> string\n\n\
6934 Return a unique name for a temporary file.");
6937 posix_tmpnam(PyObject
*self
, PyObject
*noargs
)
6939 char buffer
[L_tmpnam
];
6942 if (PyErr_Warn(PyExc_RuntimeWarning
,
6943 "tmpnam is a potential security risk to your program") < 0)
6947 name
= tmpnam_r(buffer
);
6949 name
= tmpnam(buffer
);
6952 PyObject
*err
= Py_BuildValue("is", 0,
6954 "unexpected NULL from tmpnam_r"
6956 "unexpected NULL from tmpnam"
6959 PyErr_SetObject(PyExc_OSError
, err
);
6963 return PyString_FromString(buffer
);
6968 /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
6969 * It maps strings representing configuration variable names to
6970 * integer values, allowing those functions to be called with the
6971 * magic names instead of polluting the module's namespace with tons of
6972 * rarely-used constants. There are three separate tables that use
6973 * these definitions.
6975 * This code is always included, even if none of the interfaces that
6976 * need it are included. The #if hackery needed to avoid it would be
6977 * sufficiently pervasive that it's not worth the loss of readability.
6985 conv_confname(PyObject
*arg
, int *valuep
, struct constdef
*table
,
6988 if (PyInt_Check(arg
)) {
6989 *valuep
= PyInt_AS_LONG(arg
);
6992 if (PyString_Check(arg
)) {
6993 /* look up the value in the table using a binary search */
6996 size_t hi
= tablesize
;
6998 char *confname
= PyString_AS_STRING(arg
);
7000 mid
= (lo
+ hi
) / 2;
7001 cmp
= strcmp(confname
, table
[mid
].name
);
7007 *valuep
= table
[mid
].value
;
7011 PyErr_SetString(PyExc_ValueError
, "unrecognized configuration name");
7014 PyErr_SetString(PyExc_TypeError
,
7015 "configuration names must be strings or integers");
7020 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
7021 static struct constdef posix_constants_pathconf
[] = {
7022 #ifdef _PC_ABI_AIO_XFER_MAX
7023 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX
},
7025 #ifdef _PC_ABI_ASYNC_IO
7026 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO
},
7029 {"PC_ASYNC_IO", _PC_ASYNC_IO
},
7031 #ifdef _PC_CHOWN_RESTRICTED
7032 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED
},
7034 #ifdef _PC_FILESIZEBITS
7035 {"PC_FILESIZEBITS", _PC_FILESIZEBITS
},
7038 {"PC_LAST", _PC_LAST
},
7041 {"PC_LINK_MAX", _PC_LINK_MAX
},
7043 #ifdef _PC_MAX_CANON
7044 {"PC_MAX_CANON", _PC_MAX_CANON
},
7046 #ifdef _PC_MAX_INPUT
7047 {"PC_MAX_INPUT", _PC_MAX_INPUT
},
7050 {"PC_NAME_MAX", _PC_NAME_MAX
},
7053 {"PC_NO_TRUNC", _PC_NO_TRUNC
},
7056 {"PC_PATH_MAX", _PC_PATH_MAX
},
7059 {"PC_PIPE_BUF", _PC_PIPE_BUF
},
7062 {"PC_PRIO_IO", _PC_PRIO_IO
},
7064 #ifdef _PC_SOCK_MAXBUF
7065 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF
},
7068 {"PC_SYNC_IO", _PC_SYNC_IO
},
7071 {"PC_VDISABLE", _PC_VDISABLE
},
7076 conv_path_confname(PyObject
*arg
, int *valuep
)
7078 return conv_confname(arg
, valuep
, posix_constants_pathconf
,
7079 sizeof(posix_constants_pathconf
)
7080 / sizeof(struct constdef
));
7084 #ifdef HAVE_FPATHCONF
7085 PyDoc_STRVAR(posix_fpathconf__doc__
,
7086 "fpathconf(fd, name) -> integer\n\n\
7087 Return the configuration limit name for the file descriptor fd.\n\
7088 If there is no limit, return -1.");
7091 posix_fpathconf(PyObject
*self
, PyObject
*args
)
7093 PyObject
*result
= NULL
;
7096 if (PyArg_ParseTuple(args
, "iO&:fpathconf", &fd
,
7097 conv_path_confname
, &name
)) {
7101 limit
= fpathconf(fd
, name
);
7102 if (limit
== -1 && errno
!= 0)
7105 result
= PyInt_FromLong(limit
);
7112 #ifdef HAVE_PATHCONF
7113 PyDoc_STRVAR(posix_pathconf__doc__
,
7114 "pathconf(path, name) -> integer\n\n\
7115 Return the configuration limit name for the file or directory path.\n\
7116 If there is no limit, return -1.");
7119 posix_pathconf(PyObject
*self
, PyObject
*args
)
7121 PyObject
*result
= NULL
;
7125 if (PyArg_ParseTuple(args
, "sO&:pathconf", &path
,
7126 conv_path_confname
, &name
)) {
7130 limit
= pathconf(path
, name
);
7131 if (limit
== -1 && errno
!= 0) {
7132 if (errno
== EINVAL
)
7133 /* could be a path or name problem */
7136 posix_error_with_filename(path
);
7139 result
= PyInt_FromLong(limit
);
7146 static struct constdef posix_constants_confstr
[] = {
7147 #ifdef _CS_ARCHITECTURE
7148 {"CS_ARCHITECTURE", _CS_ARCHITECTURE
},
7151 {"CS_HOSTNAME", _CS_HOSTNAME
},
7153 #ifdef _CS_HW_PROVIDER
7154 {"CS_HW_PROVIDER", _CS_HW_PROVIDER
},
7156 #ifdef _CS_HW_SERIAL
7157 {"CS_HW_SERIAL", _CS_HW_SERIAL
},
7159 #ifdef _CS_INITTAB_NAME
7160 {"CS_INITTAB_NAME", _CS_INITTAB_NAME
},
7162 #ifdef _CS_LFS64_CFLAGS
7163 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS
},
7165 #ifdef _CS_LFS64_LDFLAGS
7166 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS
},
7168 #ifdef _CS_LFS64_LIBS
7169 {"CS_LFS64_LIBS", _CS_LFS64_LIBS
},
7171 #ifdef _CS_LFS64_LINTFLAGS
7172 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS
},
7174 #ifdef _CS_LFS_CFLAGS
7175 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS
},
7177 #ifdef _CS_LFS_LDFLAGS
7178 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS
},
7181 {"CS_LFS_LIBS", _CS_LFS_LIBS
},
7183 #ifdef _CS_LFS_LINTFLAGS
7184 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS
},
7187 {"CS_MACHINE", _CS_MACHINE
},
7190 {"CS_PATH", _CS_PATH
},
7193 {"CS_RELEASE", _CS_RELEASE
},
7195 #ifdef _CS_SRPC_DOMAIN
7196 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN
},
7199 {"CS_SYSNAME", _CS_SYSNAME
},
7202 {"CS_VERSION", _CS_VERSION
},
7204 #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
7205 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS
},
7207 #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
7208 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS
},
7210 #ifdef _CS_XBS5_ILP32_OFF32_LIBS
7211 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS
},
7213 #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
7214 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS
},
7216 #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
7217 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS
},
7219 #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
7220 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS
},
7222 #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
7223 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS
},
7225 #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
7226 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
},
7228 #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
7229 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS
},
7231 #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
7232 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS
},
7234 #ifdef _CS_XBS5_LP64_OFF64_LIBS
7235 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS
},
7237 #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
7238 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS
},
7240 #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
7241 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS
},
7243 #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
7244 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
},
7246 #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
7247 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS
},
7249 #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
7250 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
},
7252 #ifdef _MIPS_CS_AVAIL_PROCESSORS
7253 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS
},
7255 #ifdef _MIPS_CS_BASE
7256 {"MIPS_CS_BASE", _MIPS_CS_BASE
},
7258 #ifdef _MIPS_CS_HOSTID
7259 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID
},
7261 #ifdef _MIPS_CS_HW_NAME
7262 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME
},
7264 #ifdef _MIPS_CS_NUM_PROCESSORS
7265 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS
},
7267 #ifdef _MIPS_CS_OSREL_MAJ
7268 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ
},
7270 #ifdef _MIPS_CS_OSREL_MIN
7271 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN
},
7273 #ifdef _MIPS_CS_OSREL_PATCH
7274 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH
},
7276 #ifdef _MIPS_CS_OS_NAME
7277 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME
},
7279 #ifdef _MIPS_CS_OS_PROVIDER
7280 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER
},
7282 #ifdef _MIPS_CS_PROCESSORS
7283 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS
},
7285 #ifdef _MIPS_CS_SERIAL
7286 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL
},
7288 #ifdef _MIPS_CS_VENDOR
7289 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR
},
7294 conv_confstr_confname(PyObject
*arg
, int *valuep
)
7296 return conv_confname(arg
, valuep
, posix_constants_confstr
,
7297 sizeof(posix_constants_confstr
)
7298 / sizeof(struct constdef
));
7301 PyDoc_STRVAR(posix_confstr__doc__
,
7302 "confstr(name) -> string\n\n\
7303 Return a string-valued system configuration variable.");
7306 posix_confstr(PyObject
*self
, PyObject
*args
)
7308 PyObject
*result
= NULL
;
7312 if (PyArg_ParseTuple(args
, "O&:confstr", conv_confstr_confname
, &name
)) {
7316 len
= confstr(name
, buffer
, sizeof(buffer
));
7327 if ((unsigned int)len
>= sizeof(buffer
)) {
7328 result
= PyString_FromStringAndSize(NULL
, len
-1);
7330 confstr(name
, PyString_AS_STRING(result
), len
);
7333 result
= PyString_FromStringAndSize(buffer
, len
-1);
7342 static struct constdef posix_constants_sysconf
[] = {
7343 #ifdef _SC_2_CHAR_TERM
7344 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM
},
7347 {"SC_2_C_BIND", _SC_2_C_BIND
},
7350 {"SC_2_C_DEV", _SC_2_C_DEV
},
7352 #ifdef _SC_2_C_VERSION
7353 {"SC_2_C_VERSION", _SC_2_C_VERSION
},
7355 #ifdef _SC_2_FORT_DEV
7356 {"SC_2_FORT_DEV", _SC_2_FORT_DEV
},
7358 #ifdef _SC_2_FORT_RUN
7359 {"SC_2_FORT_RUN", _SC_2_FORT_RUN
},
7361 #ifdef _SC_2_LOCALEDEF
7362 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF
},
7365 {"SC_2_SW_DEV", _SC_2_SW_DEV
},
7368 {"SC_2_UPE", _SC_2_UPE
},
7370 #ifdef _SC_2_VERSION
7371 {"SC_2_VERSION", _SC_2_VERSION
},
7373 #ifdef _SC_ABI_ASYNCHRONOUS_IO
7374 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO
},
7377 {"SC_ACL", _SC_ACL
},
7379 #ifdef _SC_AIO_LISTIO_MAX
7380 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX
},
7383 {"SC_AIO_MAX", _SC_AIO_MAX
},
7385 #ifdef _SC_AIO_PRIO_DELTA_MAX
7386 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX
},
7389 {"SC_ARG_MAX", _SC_ARG_MAX
},
7391 #ifdef _SC_ASYNCHRONOUS_IO
7392 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO
},
7394 #ifdef _SC_ATEXIT_MAX
7395 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX
},
7398 {"SC_AUDIT", _SC_AUDIT
},
7400 #ifdef _SC_AVPHYS_PAGES
7401 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES
},
7403 #ifdef _SC_BC_BASE_MAX
7404 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX
},
7406 #ifdef _SC_BC_DIM_MAX
7407 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX
},
7409 #ifdef _SC_BC_SCALE_MAX
7410 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX
},
7412 #ifdef _SC_BC_STRING_MAX
7413 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX
},
7416 {"SC_CAP", _SC_CAP
},
7418 #ifdef _SC_CHARCLASS_NAME_MAX
7419 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX
},
7422 {"SC_CHAR_BIT", _SC_CHAR_BIT
},
7425 {"SC_CHAR_MAX", _SC_CHAR_MAX
},
7428 {"SC_CHAR_MIN", _SC_CHAR_MIN
},
7430 #ifdef _SC_CHILD_MAX
7431 {"SC_CHILD_MAX", _SC_CHILD_MAX
},
7434 {"SC_CLK_TCK", _SC_CLK_TCK
},
7436 #ifdef _SC_COHER_BLKSZ
7437 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ
},
7439 #ifdef _SC_COLL_WEIGHTS_MAX
7440 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX
},
7442 #ifdef _SC_DCACHE_ASSOC
7443 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC
},
7445 #ifdef _SC_DCACHE_BLKSZ
7446 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ
},
7448 #ifdef _SC_DCACHE_LINESZ
7449 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ
},
7451 #ifdef _SC_DCACHE_SZ
7452 {"SC_DCACHE_SZ", _SC_DCACHE_SZ
},
7454 #ifdef _SC_DCACHE_TBLKSZ
7455 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ
},
7457 #ifdef _SC_DELAYTIMER_MAX
7458 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX
},
7460 #ifdef _SC_EQUIV_CLASS_MAX
7461 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX
},
7463 #ifdef _SC_EXPR_NEST_MAX
7464 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX
},
7467 {"SC_FSYNC", _SC_FSYNC
},
7469 #ifdef _SC_GETGR_R_SIZE_MAX
7470 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX
},
7472 #ifdef _SC_GETPW_R_SIZE_MAX
7473 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX
},
7475 #ifdef _SC_ICACHE_ASSOC
7476 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC
},
7478 #ifdef _SC_ICACHE_BLKSZ
7479 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ
},
7481 #ifdef _SC_ICACHE_LINESZ
7482 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ
},
7484 #ifdef _SC_ICACHE_SZ
7485 {"SC_ICACHE_SZ", _SC_ICACHE_SZ
},
7488 {"SC_INF", _SC_INF
},
7491 {"SC_INT_MAX", _SC_INT_MAX
},
7494 {"SC_INT_MIN", _SC_INT_MIN
},
7497 {"SC_IOV_MAX", _SC_IOV_MAX
},
7499 #ifdef _SC_IP_SECOPTS
7500 {"SC_IP_SECOPTS", _SC_IP_SECOPTS
},
7502 #ifdef _SC_JOB_CONTROL
7503 {"SC_JOB_CONTROL", _SC_JOB_CONTROL
},
7505 #ifdef _SC_KERN_POINTERS
7506 {"SC_KERN_POINTERS", _SC_KERN_POINTERS
},
7509 {"SC_KERN_SIM", _SC_KERN_SIM
},
7512 {"SC_LINE_MAX", _SC_LINE_MAX
},
7514 #ifdef _SC_LOGIN_NAME_MAX
7515 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX
},
7517 #ifdef _SC_LOGNAME_MAX
7518 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX
},
7521 {"SC_LONG_BIT", _SC_LONG_BIT
},
7524 {"SC_MAC", _SC_MAC
},
7526 #ifdef _SC_MAPPED_FILES
7527 {"SC_MAPPED_FILES", _SC_MAPPED_FILES
},
7530 {"SC_MAXPID", _SC_MAXPID
},
7532 #ifdef _SC_MB_LEN_MAX
7533 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX
},
7536 {"SC_MEMLOCK", _SC_MEMLOCK
},
7538 #ifdef _SC_MEMLOCK_RANGE
7539 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE
},
7541 #ifdef _SC_MEMORY_PROTECTION
7542 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION
},
7544 #ifdef _SC_MESSAGE_PASSING
7545 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING
},
7547 #ifdef _SC_MMAP_FIXED_ALIGNMENT
7548 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT
},
7550 #ifdef _SC_MQ_OPEN_MAX
7551 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX
},
7553 #ifdef _SC_MQ_PRIO_MAX
7554 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX
},
7556 #ifdef _SC_NACLS_MAX
7557 {"SC_NACLS_MAX", _SC_NACLS_MAX
},
7559 #ifdef _SC_NGROUPS_MAX
7560 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX
},
7562 #ifdef _SC_NL_ARGMAX
7563 {"SC_NL_ARGMAX", _SC_NL_ARGMAX
},
7565 #ifdef _SC_NL_LANGMAX
7566 {"SC_NL_LANGMAX", _SC_NL_LANGMAX
},
7568 #ifdef _SC_NL_MSGMAX
7569 {"SC_NL_MSGMAX", _SC_NL_MSGMAX
},
7572 {"SC_NL_NMAX", _SC_NL_NMAX
},
7574 #ifdef _SC_NL_SETMAX
7575 {"SC_NL_SETMAX", _SC_NL_SETMAX
},
7577 #ifdef _SC_NL_TEXTMAX
7578 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX
},
7580 #ifdef _SC_NPROCESSORS_CONF
7581 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF
},
7583 #ifdef _SC_NPROCESSORS_ONLN
7584 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN
},
7586 #ifdef _SC_NPROC_CONF
7587 {"SC_NPROC_CONF", _SC_NPROC_CONF
},
7589 #ifdef _SC_NPROC_ONLN
7590 {"SC_NPROC_ONLN", _SC_NPROC_ONLN
},
7593 {"SC_NZERO", _SC_NZERO
},
7596 {"SC_OPEN_MAX", _SC_OPEN_MAX
},
7599 {"SC_PAGESIZE", _SC_PAGESIZE
},
7601 #ifdef _SC_PAGE_SIZE
7602 {"SC_PAGE_SIZE", _SC_PAGE_SIZE
},
7605 {"SC_PASS_MAX", _SC_PASS_MAX
},
7607 #ifdef _SC_PHYS_PAGES
7608 {"SC_PHYS_PAGES", _SC_PHYS_PAGES
},
7611 {"SC_PII", _SC_PII
},
7613 #ifdef _SC_PII_INTERNET
7614 {"SC_PII_INTERNET", _SC_PII_INTERNET
},
7616 #ifdef _SC_PII_INTERNET_DGRAM
7617 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM
},
7619 #ifdef _SC_PII_INTERNET_STREAM
7620 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM
},
7623 {"SC_PII_OSI", _SC_PII_OSI
},
7625 #ifdef _SC_PII_OSI_CLTS
7626 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS
},
7628 #ifdef _SC_PII_OSI_COTS
7629 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS
},
7631 #ifdef _SC_PII_OSI_M
7632 {"SC_PII_OSI_M", _SC_PII_OSI_M
},
7634 #ifdef _SC_PII_SOCKET
7635 {"SC_PII_SOCKET", _SC_PII_SOCKET
},
7638 {"SC_PII_XTI", _SC_PII_XTI
},
7641 {"SC_POLL", _SC_POLL
},
7643 #ifdef _SC_PRIORITIZED_IO
7644 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO
},
7646 #ifdef _SC_PRIORITY_SCHEDULING
7647 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING
},
7649 #ifdef _SC_REALTIME_SIGNALS
7650 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS
},
7652 #ifdef _SC_RE_DUP_MAX
7653 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX
},
7655 #ifdef _SC_RTSIG_MAX
7656 {"SC_RTSIG_MAX", _SC_RTSIG_MAX
},
7658 #ifdef _SC_SAVED_IDS
7659 {"SC_SAVED_IDS", _SC_SAVED_IDS
},
7661 #ifdef _SC_SCHAR_MAX
7662 {"SC_SCHAR_MAX", _SC_SCHAR_MAX
},
7664 #ifdef _SC_SCHAR_MIN
7665 {"SC_SCHAR_MIN", _SC_SCHAR_MIN
},
7668 {"SC_SELECT", _SC_SELECT
},
7670 #ifdef _SC_SEMAPHORES
7671 {"SC_SEMAPHORES", _SC_SEMAPHORES
},
7673 #ifdef _SC_SEM_NSEMS_MAX
7674 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX
},
7676 #ifdef _SC_SEM_VALUE_MAX
7677 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX
},
7679 #ifdef _SC_SHARED_MEMORY_OBJECTS
7680 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS
},
7683 {"SC_SHRT_MAX", _SC_SHRT_MAX
},
7686 {"SC_SHRT_MIN", _SC_SHRT_MIN
},
7688 #ifdef _SC_SIGQUEUE_MAX
7689 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX
},
7691 #ifdef _SC_SIGRT_MAX
7692 {"SC_SIGRT_MAX", _SC_SIGRT_MAX
},
7694 #ifdef _SC_SIGRT_MIN
7695 {"SC_SIGRT_MIN", _SC_SIGRT_MIN
},
7697 #ifdef _SC_SOFTPOWER
7698 {"SC_SOFTPOWER", _SC_SOFTPOWER
},
7700 #ifdef _SC_SPLIT_CACHE
7701 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE
},
7703 #ifdef _SC_SSIZE_MAX
7704 {"SC_SSIZE_MAX", _SC_SSIZE_MAX
},
7706 #ifdef _SC_STACK_PROT
7707 {"SC_STACK_PROT", _SC_STACK_PROT
},
7709 #ifdef _SC_STREAM_MAX
7710 {"SC_STREAM_MAX", _SC_STREAM_MAX
},
7712 #ifdef _SC_SYNCHRONIZED_IO
7713 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO
},
7716 {"SC_THREADS", _SC_THREADS
},
7718 #ifdef _SC_THREAD_ATTR_STACKADDR
7719 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR
},
7721 #ifdef _SC_THREAD_ATTR_STACKSIZE
7722 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE
},
7724 #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
7725 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS
},
7727 #ifdef _SC_THREAD_KEYS_MAX
7728 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX
},
7730 #ifdef _SC_THREAD_PRIORITY_SCHEDULING
7731 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING
},
7733 #ifdef _SC_THREAD_PRIO_INHERIT
7734 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT
},
7736 #ifdef _SC_THREAD_PRIO_PROTECT
7737 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT
},
7739 #ifdef _SC_THREAD_PROCESS_SHARED
7740 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED
},
7742 #ifdef _SC_THREAD_SAFE_FUNCTIONS
7743 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS
},
7745 #ifdef _SC_THREAD_STACK_MIN
7746 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN
},
7748 #ifdef _SC_THREAD_THREADS_MAX
7749 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX
},
7752 {"SC_TIMERS", _SC_TIMERS
},
7754 #ifdef _SC_TIMER_MAX
7755 {"SC_TIMER_MAX", _SC_TIMER_MAX
},
7757 #ifdef _SC_TTY_NAME_MAX
7758 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX
},
7760 #ifdef _SC_TZNAME_MAX
7761 {"SC_TZNAME_MAX", _SC_TZNAME_MAX
},
7763 #ifdef _SC_T_IOV_MAX
7764 {"SC_T_IOV_MAX", _SC_T_IOV_MAX
},
7766 #ifdef _SC_UCHAR_MAX
7767 {"SC_UCHAR_MAX", _SC_UCHAR_MAX
},
7770 {"SC_UINT_MAX", _SC_UINT_MAX
},
7772 #ifdef _SC_UIO_MAXIOV
7773 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV
},
7775 #ifdef _SC_ULONG_MAX
7776 {"SC_ULONG_MAX", _SC_ULONG_MAX
},
7778 #ifdef _SC_USHRT_MAX
7779 {"SC_USHRT_MAX", _SC_USHRT_MAX
},
7782 {"SC_VERSION", _SC_VERSION
},
7785 {"SC_WORD_BIT", _SC_WORD_BIT
},
7787 #ifdef _SC_XBS5_ILP32_OFF32
7788 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32
},
7790 #ifdef _SC_XBS5_ILP32_OFFBIG
7791 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG
},
7793 #ifdef _SC_XBS5_LP64_OFF64
7794 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64
},
7796 #ifdef _SC_XBS5_LPBIG_OFFBIG
7797 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG
},
7799 #ifdef _SC_XOPEN_CRYPT
7800 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT
},
7802 #ifdef _SC_XOPEN_ENH_I18N
7803 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N
},
7805 #ifdef _SC_XOPEN_LEGACY
7806 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY
},
7808 #ifdef _SC_XOPEN_REALTIME
7809 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME
},
7811 #ifdef _SC_XOPEN_REALTIME_THREADS
7812 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS
},
7814 #ifdef _SC_XOPEN_SHM
7815 {"SC_XOPEN_SHM", _SC_XOPEN_SHM
},
7817 #ifdef _SC_XOPEN_UNIX
7818 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX
},
7820 #ifdef _SC_XOPEN_VERSION
7821 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION
},
7823 #ifdef _SC_XOPEN_XCU_VERSION
7824 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION
},
7826 #ifdef _SC_XOPEN_XPG2
7827 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2
},
7829 #ifdef _SC_XOPEN_XPG3
7830 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3
},
7832 #ifdef _SC_XOPEN_XPG4
7833 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4
},
7838 conv_sysconf_confname(PyObject
*arg
, int *valuep
)
7840 return conv_confname(arg
, valuep
, posix_constants_sysconf
,
7841 sizeof(posix_constants_sysconf
)
7842 / sizeof(struct constdef
));
7845 PyDoc_STRVAR(posix_sysconf__doc__
,
7846 "sysconf(name) -> integer\n\n\
7847 Return an integer-valued system configuration variable.");
7850 posix_sysconf(PyObject
*self
, PyObject
*args
)
7852 PyObject
*result
= NULL
;
7855 if (PyArg_ParseTuple(args
, "O&:sysconf", conv_sysconf_confname
, &name
)) {
7859 value
= sysconf(name
);
7860 if (value
== -1 && errno
!= 0)
7863 result
= PyInt_FromLong(value
);
7870 /* This code is used to ensure that the tables of configuration value names
7871 * are in sorted order as required by conv_confname(), and also to build the
7872 * the exported dictionaries that are used to publish information about the
7873 * names available on the host platform.
7875 * Sorting the table at runtime ensures that the table is properly ordered
7876 * when used, even for platforms we're not able to test on. It also makes
7877 * it easier to add additional entries to the tables.
7881 cmp_constdefs(const void *v1
, const void *v2
)
7883 const struct constdef
*c1
=
7884 (const struct constdef
*) v1
;
7885 const struct constdef
*c2
=
7886 (const struct constdef
*) v2
;
7888 return strcmp(c1
->name
, c2
->name
);
7892 setup_confname_table(struct constdef
*table
, size_t tablesize
,
7893 char *tablename
, PyObject
*module
)
7898 qsort(table
, tablesize
, sizeof(struct constdef
), cmp_constdefs
);
7903 for (i
=0; i
< tablesize
; ++i
) {
7904 PyObject
*o
= PyInt_FromLong(table
[i
].value
);
7905 if (o
== NULL
|| PyDict_SetItemString(d
, table
[i
].name
, o
) == -1) {
7912 return PyModule_AddObject(module
, tablename
, d
);
7915 /* Return -1 on failure, 0 on success. */
7917 setup_confname_tables(PyObject
*module
)
7919 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
7920 if (setup_confname_table(posix_constants_pathconf
,
7921 sizeof(posix_constants_pathconf
)
7922 / sizeof(struct constdef
),
7923 "pathconf_names", module
))
7927 if (setup_confname_table(posix_constants_confstr
,
7928 sizeof(posix_constants_confstr
)
7929 / sizeof(struct constdef
),
7930 "confstr_names", module
))
7934 if (setup_confname_table(posix_constants_sysconf
,
7935 sizeof(posix_constants_sysconf
)
7936 / sizeof(struct constdef
),
7937 "sysconf_names", module
))
7944 PyDoc_STRVAR(posix_abort__doc__
,
7945 "abort() -> does not return!\n\n\
7946 Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\
7947 in the hardest way possible on the hosting operating system.");
7950 posix_abort(PyObject
*self
, PyObject
*noargs
)
7954 Py_FatalError("abort() called from Python code didn't abort!");
7959 PyDoc_STRVAR(win32_startfile__doc__
,
7960 "startfile(filepath [, operation]) - Start a file with its associated\n\
7963 When \"operation\" is not specified or \"open\", this acts like\n\
7964 double-clicking the file in Explorer, or giving the file name as an\n\
7965 argument to the DOS \"start\" command: the file is opened with whatever\n\
7966 application (if any) its extension is associated.\n\
7967 When another \"operation\" is given, it specifies what should be done with\n\
7968 the file. A typical operation is \"print\".\n\
7970 startfile returns as soon as the associated application is launched.\n\
7971 There is no option to wait for the application to close, and no way\n\
7972 to retrieve the application's exit status.\n\
7974 The filepath is relative to the current directory. If you want to use\n\
7975 an absolute path, make sure the first character is not a slash (\"/\");\n\
7976 the underlying Win32 ShellExecute function doesn't work if it is.");
7979 win32_startfile(PyObject
*self
, PyObject
*args
)
7982 char *operation
= NULL
;
7984 #ifdef Py_WIN_WIDE_FILENAMES
7985 if (unicode_file_names()) {
7986 PyObject
*unipath
, *woperation
= NULL
;
7987 if (!PyArg_ParseTuple(args
, "U|s:startfile",
7988 &unipath
, &operation
)) {
7995 woperation
= PyUnicode_DecodeASCII(operation
,
7996 strlen(operation
), NULL
);
8004 Py_BEGIN_ALLOW_THREADS
8005 rc
= ShellExecuteW((HWND
)0, woperation
? PyUnicode_AS_UNICODE(woperation
) : 0,
8006 PyUnicode_AS_UNICODE(unipath
),
8007 NULL
, NULL
, SW_SHOWNORMAL
);
8008 Py_END_ALLOW_THREADS
8010 Py_XDECREF(woperation
);
8011 if (rc
<= (HINSTANCE
)32) {
8012 PyObject
*errval
= win32_error_unicode("startfile",
8013 PyUnicode_AS_UNICODE(unipath
));
8022 if (!PyArg_ParseTuple(args
, "et|s:startfile",
8023 Py_FileSystemDefaultEncoding
, &filepath
,
8026 Py_BEGIN_ALLOW_THREADS
8027 rc
= ShellExecute((HWND
)0, operation
, filepath
,
8028 NULL
, NULL
, SW_SHOWNORMAL
);
8029 Py_END_ALLOW_THREADS
8030 if (rc
<= (HINSTANCE
)32) {
8031 PyObject
*errval
= win32_error("startfile", filepath
);
8032 PyMem_Free(filepath
);
8035 PyMem_Free(filepath
);
8041 #ifdef HAVE_GETLOADAVG
8042 PyDoc_STRVAR(posix_getloadavg__doc__
,
8043 "getloadavg() -> (float, float, float)\n\n\
8044 Return the number of processes in the system run queue averaged over\n\
8045 the last 1, 5, and 15 minutes or raises OSError if the load average\n\
8049 posix_getloadavg(PyObject
*self
, PyObject
*noargs
)
8052 if (getloadavg(loadavg
, 3)!=3) {
8053 PyErr_SetString(PyExc_OSError
, "Load averages are unobtainable");
8056 return Py_BuildValue("ddd", loadavg
[0], loadavg
[1], loadavg
[2]);
8062 PyDoc_STRVAR(win32_urandom__doc__
,
8063 "urandom(n) -> str\n\n\
8064 Return a string of n random bytes suitable for cryptographic use.");
8066 typedef BOOL (WINAPI
*CRYPTACQUIRECONTEXTA
)(HCRYPTPROV
*phProv
,\
8067 LPCSTR pszContainer
, LPCSTR pszProvider
, DWORD dwProvType
,\
8069 typedef BOOL (WINAPI
*CRYPTGENRANDOM
)(HCRYPTPROV hProv
, DWORD dwLen
,\
8072 static CRYPTGENRANDOM pCryptGenRandom
= NULL
;
8073 static HCRYPTPROV hCryptProv
= 0;
8076 win32_urandom(PyObject
*self
, PyObject
*args
)
8081 /* Read arguments */
8082 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8085 return PyErr_Format(PyExc_ValueError
,
8086 "negative argument not allowed");
8088 if (hCryptProv
== 0) {
8089 HINSTANCE hAdvAPI32
= NULL
;
8090 CRYPTACQUIRECONTEXTA pCryptAcquireContext
= NULL
;
8092 /* Obtain handle to the DLL containing CryptoAPI
8093 This should not fail */
8094 hAdvAPI32
= GetModuleHandle("advapi32.dll");
8095 if(hAdvAPI32
== NULL
)
8096 return win32_error("GetModuleHandle", NULL
);
8098 /* Obtain pointers to the CryptoAPI functions
8099 This will fail on some early versions of Win95 */
8100 pCryptAcquireContext
= (CRYPTACQUIRECONTEXTA
)GetProcAddress(
8102 "CryptAcquireContextA");
8103 if (pCryptAcquireContext
== NULL
)
8104 return PyErr_Format(PyExc_NotImplementedError
,
8105 "CryptAcquireContextA not found");
8107 pCryptGenRandom
= (CRYPTGENRANDOM
)GetProcAddress(
8108 hAdvAPI32
, "CryptGenRandom");
8109 if (pCryptGenRandom
== NULL
)
8110 return PyErr_Format(PyExc_NotImplementedError
,
8111 "CryptGenRandom not found");
8113 /* Acquire context */
8114 if (! pCryptAcquireContext(&hCryptProv
, NULL
, NULL
,
8115 PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
))
8116 return win32_error("CryptAcquireContext", NULL
);
8119 /* Allocate bytes */
8120 result
= PyString_FromStringAndSize(NULL
, howMany
);
8121 if (result
!= NULL
) {
8122 /* Get random data */
8123 if (! pCryptGenRandom(hCryptProv
, howMany
, (unsigned char*)
8124 PyString_AS_STRING(result
))) {
8126 return win32_error("CryptGenRandom", NULL
);
8134 /* Use openssl random routine */
8135 #include <openssl/rand.h>
8136 PyDoc_STRVAR(vms_urandom__doc__
,
8137 "urandom(n) -> str\n\n\
8138 Return a string of n random bytes suitable for cryptographic use.");
8141 vms_urandom(PyObject
*self
, PyObject
*args
)
8146 /* Read arguments */
8147 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8150 return PyErr_Format(PyExc_ValueError
,
8151 "negative argument not allowed");
8153 /* Allocate bytes */
8154 result
= PyString_FromStringAndSize(NULL
, howMany
);
8155 if (result
!= NULL
) {
8156 /* Get random data */
8157 if (RAND_pseudo_bytes((unsigned char*)
8158 PyString_AS_STRING(result
),
8161 return PyErr_Format(PyExc_ValueError
,
8162 "RAND_pseudo_bytes");
8169 static PyMethodDef posix_methods
[] = {
8170 {"access", posix_access
, METH_VARARGS
, posix_access__doc__
},
8172 {"ttyname", posix_ttyname
, METH_VARARGS
, posix_ttyname__doc__
},
8174 {"chdir", posix_chdir
, METH_VARARGS
, posix_chdir__doc__
},
8176 {"chflags", posix_chflags
, METH_VARARGS
, posix_chflags__doc__
},
8177 #endif /* HAVE_CHFLAGS */
8178 {"chmod", posix_chmod
, METH_VARARGS
, posix_chmod__doc__
},
8180 {"chown", posix_chown
, METH_VARARGS
, posix_chown__doc__
},
8181 #endif /* HAVE_CHOWN */
8182 #ifdef HAVE_LCHFLAGS
8183 {"lchflags", posix_lchflags
, METH_VARARGS
, posix_lchflags__doc__
},
8184 #endif /* HAVE_LCHFLAGS */
8186 {"lchown", posix_lchown
, METH_VARARGS
, posix_lchown__doc__
},
8187 #endif /* HAVE_LCHOWN */
8189 {"chroot", posix_chroot
, METH_VARARGS
, posix_chroot__doc__
},
8192 {"ctermid", posix_ctermid
, METH_NOARGS
, posix_ctermid__doc__
},
8195 {"getcwd", posix_getcwd
, METH_NOARGS
, posix_getcwd__doc__
},
8196 #ifdef Py_USING_UNICODE
8197 {"getcwdu", posix_getcwdu
, METH_NOARGS
, posix_getcwdu__doc__
},
8201 {"link", posix_link
, METH_VARARGS
, posix_link__doc__
},
8202 #endif /* HAVE_LINK */
8203 {"listdir", posix_listdir
, METH_VARARGS
, posix_listdir__doc__
},
8204 {"lstat", posix_lstat
, METH_VARARGS
, posix_lstat__doc__
},
8205 {"mkdir", posix_mkdir
, METH_VARARGS
, posix_mkdir__doc__
},
8207 {"nice", posix_nice
, METH_VARARGS
, posix_nice__doc__
},
8208 #endif /* HAVE_NICE */
8209 #ifdef HAVE_READLINK
8210 {"readlink", posix_readlink
, METH_VARARGS
, posix_readlink__doc__
},
8211 #endif /* HAVE_READLINK */
8212 {"rename", posix_rename
, METH_VARARGS
, posix_rename__doc__
},
8213 {"rmdir", posix_rmdir
, METH_VARARGS
, posix_rmdir__doc__
},
8214 {"stat", posix_stat
, METH_VARARGS
, posix_stat__doc__
},
8215 {"stat_float_times", stat_float_times
, METH_VARARGS
, stat_float_times__doc__
},
8217 {"symlink", posix_symlink
, METH_VARARGS
, posix_symlink__doc__
},
8218 #endif /* HAVE_SYMLINK */
8220 {"system", posix_system
, METH_VARARGS
, posix_system__doc__
},
8222 {"umask", posix_umask
, METH_VARARGS
, posix_umask__doc__
},
8224 {"uname", posix_uname
, METH_NOARGS
, posix_uname__doc__
},
8225 #endif /* HAVE_UNAME */
8226 {"unlink", posix_unlink
, METH_VARARGS
, posix_unlink__doc__
},
8227 {"remove", posix_unlink
, METH_VARARGS
, posix_remove__doc__
},
8228 {"utime", posix_utime
, METH_VARARGS
, posix_utime__doc__
},
8230 {"times", posix_times
, METH_NOARGS
, posix_times__doc__
},
8231 #endif /* HAVE_TIMES */
8232 {"_exit", posix__exit
, METH_VARARGS
, posix__exit__doc__
},
8234 {"execv", posix_execv
, METH_VARARGS
, posix_execv__doc__
},
8235 {"execve", posix_execve
, METH_VARARGS
, posix_execve__doc__
},
8236 #endif /* HAVE_EXECV */
8238 {"spawnv", posix_spawnv
, METH_VARARGS
, posix_spawnv__doc__
},
8239 {"spawnve", posix_spawnve
, METH_VARARGS
, posix_spawnve__doc__
},
8240 #if defined(PYOS_OS2)
8241 {"spawnvp", posix_spawnvp
, METH_VARARGS
, posix_spawnvp__doc__
},
8242 {"spawnvpe", posix_spawnvpe
, METH_VARARGS
, posix_spawnvpe__doc__
},
8243 #endif /* PYOS_OS2 */
8244 #endif /* HAVE_SPAWNV */
8246 {"fork1", posix_fork1
, METH_NOARGS
, posix_fork1__doc__
},
8247 #endif /* HAVE_FORK1 */
8249 {"fork", posix_fork
, METH_NOARGS
, posix_fork__doc__
},
8250 #endif /* HAVE_FORK */
8251 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
8252 {"openpty", posix_openpty
, METH_NOARGS
, posix_openpty__doc__
},
8253 #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
8255 {"forkpty", posix_forkpty
, METH_NOARGS
, posix_forkpty__doc__
},
8256 #endif /* HAVE_FORKPTY */
8258 {"getegid", posix_getegid
, METH_NOARGS
, posix_getegid__doc__
},
8259 #endif /* HAVE_GETEGID */
8261 {"geteuid", posix_geteuid
, METH_NOARGS
, posix_geteuid__doc__
},
8262 #endif /* HAVE_GETEUID */
8264 {"getgid", posix_getgid
, METH_NOARGS
, posix_getgid__doc__
},
8265 #endif /* HAVE_GETGID */
8266 #ifdef HAVE_GETGROUPS
8267 {"getgroups", posix_getgroups
, METH_NOARGS
, posix_getgroups__doc__
},
8269 {"getpid", posix_getpid
, METH_NOARGS
, posix_getpid__doc__
},
8271 {"getpgrp", posix_getpgrp
, METH_NOARGS
, posix_getpgrp__doc__
},
8272 #endif /* HAVE_GETPGRP */
8274 {"getppid", posix_getppid
, METH_NOARGS
, posix_getppid__doc__
},
8275 #endif /* HAVE_GETPPID */
8277 {"getuid", posix_getuid
, METH_NOARGS
, posix_getuid__doc__
},
8278 #endif /* HAVE_GETUID */
8279 #ifdef HAVE_GETLOGIN
8280 {"getlogin", posix_getlogin
, METH_NOARGS
, posix_getlogin__doc__
},
8283 {"kill", posix_kill
, METH_VARARGS
, posix_kill__doc__
},
8284 #endif /* HAVE_KILL */
8286 {"killpg", posix_killpg
, METH_VARARGS
, posix_killpg__doc__
},
8287 #endif /* HAVE_KILLPG */
8289 {"plock", posix_plock
, METH_VARARGS
, posix_plock__doc__
},
8290 #endif /* HAVE_PLOCK */
8292 {"popen", posix_popen
, METH_VARARGS
, posix_popen__doc__
},
8294 {"popen2", win32_popen2
, METH_VARARGS
},
8295 {"popen3", win32_popen3
, METH_VARARGS
},
8296 {"popen4", win32_popen4
, METH_VARARGS
},
8297 {"startfile", win32_startfile
, METH_VARARGS
, win32_startfile__doc__
},
8299 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8300 {"popen2", os2emx_popen2
, METH_VARARGS
},
8301 {"popen3", os2emx_popen3
, METH_VARARGS
},
8302 {"popen4", os2emx_popen4
, METH_VARARGS
},
8305 #endif /* HAVE_POPEN */
8307 {"setuid", posix_setuid
, METH_VARARGS
, posix_setuid__doc__
},
8308 #endif /* HAVE_SETUID */
8310 {"seteuid", posix_seteuid
, METH_VARARGS
, posix_seteuid__doc__
},
8311 #endif /* HAVE_SETEUID */
8313 {"setegid", posix_setegid
, METH_VARARGS
, posix_setegid__doc__
},
8314 #endif /* HAVE_SETEGID */
8315 #ifdef HAVE_SETREUID
8316 {"setreuid", posix_setreuid
, METH_VARARGS
, posix_setreuid__doc__
},
8317 #endif /* HAVE_SETREUID */
8318 #ifdef HAVE_SETREGID
8319 {"setregid", posix_setregid
, METH_VARARGS
, posix_setregid__doc__
},
8320 #endif /* HAVE_SETREGID */
8322 {"setgid", posix_setgid
, METH_VARARGS
, posix_setgid__doc__
},
8323 #endif /* HAVE_SETGID */
8324 #ifdef HAVE_SETGROUPS
8325 {"setgroups", posix_setgroups
, METH_O
, posix_setgroups__doc__
},
8326 #endif /* HAVE_SETGROUPS */
8328 {"getpgid", posix_getpgid
, METH_VARARGS
, posix_getpgid__doc__
},
8329 #endif /* HAVE_GETPGID */
8331 {"setpgrp", posix_setpgrp
, METH_NOARGS
, posix_setpgrp__doc__
},
8332 #endif /* HAVE_SETPGRP */
8334 {"wait", posix_wait
, METH_NOARGS
, posix_wait__doc__
},
8335 #endif /* HAVE_WAIT */
8337 {"wait3", posix_wait3
, METH_VARARGS
, posix_wait3__doc__
},
8338 #endif /* HAVE_WAIT3 */
8340 {"wait4", posix_wait4
, METH_VARARGS
, posix_wait4__doc__
},
8341 #endif /* HAVE_WAIT4 */
8342 #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
8343 {"waitpid", posix_waitpid
, METH_VARARGS
, posix_waitpid__doc__
},
8344 #endif /* HAVE_WAITPID */
8346 {"getsid", posix_getsid
, METH_VARARGS
, posix_getsid__doc__
},
8347 #endif /* HAVE_GETSID */
8349 {"setsid", posix_setsid
, METH_NOARGS
, posix_setsid__doc__
},
8350 #endif /* HAVE_SETSID */
8352 {"setpgid", posix_setpgid
, METH_VARARGS
, posix_setpgid__doc__
},
8353 #endif /* HAVE_SETPGID */
8354 #ifdef HAVE_TCGETPGRP
8355 {"tcgetpgrp", posix_tcgetpgrp
, METH_VARARGS
, posix_tcgetpgrp__doc__
},
8356 #endif /* HAVE_TCGETPGRP */
8357 #ifdef HAVE_TCSETPGRP
8358 {"tcsetpgrp", posix_tcsetpgrp
, METH_VARARGS
, posix_tcsetpgrp__doc__
},
8359 #endif /* HAVE_TCSETPGRP */
8360 {"open", posix_open
, METH_VARARGS
, posix_open__doc__
},
8361 {"close", posix_close
, METH_VARARGS
, posix_close__doc__
},
8362 {"dup", posix_dup
, METH_VARARGS
, posix_dup__doc__
},
8363 {"dup2", posix_dup2
, METH_VARARGS
, posix_dup2__doc__
},
8364 {"lseek", posix_lseek
, METH_VARARGS
, posix_lseek__doc__
},
8365 {"read", posix_read
, METH_VARARGS
, posix_read__doc__
},
8366 {"write", posix_write
, METH_VARARGS
, posix_write__doc__
},
8367 {"fstat", posix_fstat
, METH_VARARGS
, posix_fstat__doc__
},
8368 {"fdopen", posix_fdopen
, METH_VARARGS
, posix_fdopen__doc__
},
8369 {"isatty", posix_isatty
, METH_VARARGS
, posix_isatty__doc__
},
8371 {"pipe", posix_pipe
, METH_NOARGS
, posix_pipe__doc__
},
8374 {"mkfifo", posix_mkfifo
, METH_VARARGS
, posix_mkfifo__doc__
},
8376 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
8377 {"mknod", posix_mknod
, METH_VARARGS
, posix_mknod__doc__
},
8379 #ifdef HAVE_DEVICE_MACROS
8380 {"major", posix_major
, METH_VARARGS
, posix_major__doc__
},
8381 {"minor", posix_minor
, METH_VARARGS
, posix_minor__doc__
},
8382 {"makedev", posix_makedev
, METH_VARARGS
, posix_makedev__doc__
},
8384 #ifdef HAVE_FTRUNCATE
8385 {"ftruncate", posix_ftruncate
, METH_VARARGS
, posix_ftruncate__doc__
},
8388 {"putenv", posix_putenv
, METH_VARARGS
, posix_putenv__doc__
},
8390 #ifdef HAVE_UNSETENV
8391 {"unsetenv", posix_unsetenv
, METH_VARARGS
, posix_unsetenv__doc__
},
8393 #ifdef HAVE_STRERROR
8394 {"strerror", posix_strerror
, METH_VARARGS
, posix_strerror__doc__
},
8397 {"fchdir", posix_fchdir
, METH_O
, posix_fchdir__doc__
},
8400 {"fsync", posix_fsync
, METH_O
, posix_fsync__doc__
},
8402 #ifdef HAVE_FDATASYNC
8403 {"fdatasync", posix_fdatasync
, METH_O
, posix_fdatasync__doc__
},
8405 #ifdef HAVE_SYS_WAIT_H
8407 {"WCOREDUMP", posix_WCOREDUMP
, METH_VARARGS
, posix_WCOREDUMP__doc__
},
8408 #endif /* WCOREDUMP */
8410 {"WIFCONTINUED",posix_WIFCONTINUED
, METH_VARARGS
, posix_WIFCONTINUED__doc__
},
8411 #endif /* WIFCONTINUED */
8413 {"WIFSTOPPED", posix_WIFSTOPPED
, METH_VARARGS
, posix_WIFSTOPPED__doc__
},
8414 #endif /* WIFSTOPPED */
8416 {"WIFSIGNALED", posix_WIFSIGNALED
, METH_VARARGS
, posix_WIFSIGNALED__doc__
},
8417 #endif /* WIFSIGNALED */
8419 {"WIFEXITED", posix_WIFEXITED
, METH_VARARGS
, posix_WIFEXITED__doc__
},
8420 #endif /* WIFEXITED */
8422 {"WEXITSTATUS", posix_WEXITSTATUS
, METH_VARARGS
, posix_WEXITSTATUS__doc__
},
8423 #endif /* WEXITSTATUS */
8425 {"WTERMSIG", posix_WTERMSIG
, METH_VARARGS
, posix_WTERMSIG__doc__
},
8426 #endif /* WTERMSIG */
8428 {"WSTOPSIG", posix_WSTOPSIG
, METH_VARARGS
, posix_WSTOPSIG__doc__
},
8429 #endif /* WSTOPSIG */
8430 #endif /* HAVE_SYS_WAIT_H */
8431 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
8432 {"fstatvfs", posix_fstatvfs
, METH_VARARGS
, posix_fstatvfs__doc__
},
8434 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
8435 {"statvfs", posix_statvfs
, METH_VARARGS
, posix_statvfs__doc__
},
8438 {"tmpfile", posix_tmpfile
, METH_NOARGS
, posix_tmpfile__doc__
},
8441 {"tempnam", posix_tempnam
, METH_VARARGS
, posix_tempnam__doc__
},
8444 {"tmpnam", posix_tmpnam
, METH_NOARGS
, posix_tmpnam__doc__
},
8447 {"confstr", posix_confstr
, METH_VARARGS
, posix_confstr__doc__
},
8450 {"sysconf", posix_sysconf
, METH_VARARGS
, posix_sysconf__doc__
},
8452 #ifdef HAVE_FPATHCONF
8453 {"fpathconf", posix_fpathconf
, METH_VARARGS
, posix_fpathconf__doc__
},
8455 #ifdef HAVE_PATHCONF
8456 {"pathconf", posix_pathconf
, METH_VARARGS
, posix_pathconf__doc__
},
8458 {"abort", posix_abort
, METH_NOARGS
, posix_abort__doc__
},
8460 {"_getfullpathname", posix__getfullpathname
, METH_VARARGS
, NULL
},
8462 #ifdef HAVE_GETLOADAVG
8463 {"getloadavg", posix_getloadavg
, METH_NOARGS
, posix_getloadavg__doc__
},
8466 {"urandom", win32_urandom
, METH_VARARGS
, win32_urandom__doc__
},
8469 {"urandom", vms_urandom
, METH_VARARGS
, vms_urandom__doc__
},
8471 {NULL
, NULL
} /* Sentinel */
8476 ins(PyObject
*module
, char *symbol
, long value
)
8478 return PyModule_AddIntConstant(module
, symbol
, value
);
8481 #if defined(PYOS_OS2)
8482 /* Insert Platform-Specific Constant Values (Strings & Numbers) of Common Use */
8483 static int insertvalues(PyObject
*module
)
8486 ULONG values
[QSV_MAX
+1];
8490 Py_BEGIN_ALLOW_THREADS
8491 rc
= DosQuerySysInfo(1L, QSV_MAX
, &values
[1], sizeof(ULONG
) * QSV_MAX
);
8492 Py_END_ALLOW_THREADS
8494 if (rc
!= NO_ERROR
) {
8499 if (ins(module
, "meminstalled", values
[QSV_TOTPHYSMEM
])) return -1;
8500 if (ins(module
, "memkernel", values
[QSV_TOTRESMEM
])) return -1;
8501 if (ins(module
, "memvirtual", values
[QSV_TOTAVAILMEM
])) return -1;
8502 if (ins(module
, "maxpathlen", values
[QSV_MAX_PATH_LENGTH
])) return -1;
8503 if (ins(module
, "maxnamelen", values
[QSV_MAX_COMP_LENGTH
])) return -1;
8504 if (ins(module
, "revision", values
[QSV_VERSION_REVISION
])) return -1;
8505 if (ins(module
, "timeslice", values
[QSV_MIN_SLICE
])) return -1;
8507 switch (values
[QSV_VERSION_MINOR
]) {
8508 case 0: ver
= "2.00"; break;
8509 case 10: ver
= "2.10"; break;
8510 case 11: ver
= "2.11"; break;
8511 case 30: ver
= "3.00"; break;
8512 case 40: ver
= "4.00"; break;
8513 case 50: ver
= "5.00"; break;
8515 PyOS_snprintf(tmp
, sizeof(tmp
),
8516 "%d-%d", values
[QSV_VERSION_MAJOR
],
8517 values
[QSV_VERSION_MINOR
]);
8521 /* Add Indicator of the Version of the Operating System */
8522 if (PyModule_AddStringConstant(module
, "version", tmp
) < 0)
8525 /* Add Indicator of Which Drive was Used to Boot the System */
8526 tmp
[0] = 'A' + values
[QSV_BOOT_DRIVE
] - 1;
8530 return PyModule_AddStringConstant(module
, "bootdrive", tmp
);
8535 all_ins(PyObject
*d
)
8538 if (ins(d
, "F_OK", (long)F_OK
)) return -1;
8541 if (ins(d
, "R_OK", (long)R_OK
)) return -1;
8544 if (ins(d
, "W_OK", (long)W_OK
)) return -1;
8547 if (ins(d
, "X_OK", (long)X_OK
)) return -1;
8550 if (ins(d
, "NGROUPS_MAX", (long)NGROUPS_MAX
)) return -1;
8553 if (ins(d
, "TMP_MAX", (long)TMP_MAX
)) return -1;
8556 if (ins(d
, "WCONTINUED", (long)WCONTINUED
)) return -1;
8559 if (ins(d
, "WNOHANG", (long)WNOHANG
)) return -1;
8562 if (ins(d
, "WUNTRACED", (long)WUNTRACED
)) return -1;
8565 if (ins(d
, "O_RDONLY", (long)O_RDONLY
)) return -1;
8568 if (ins(d
, "O_WRONLY", (long)O_WRONLY
)) return -1;
8571 if (ins(d
, "O_RDWR", (long)O_RDWR
)) return -1;
8574 if (ins(d
, "O_NDELAY", (long)O_NDELAY
)) return -1;
8577 if (ins(d
, "O_NONBLOCK", (long)O_NONBLOCK
)) return -1;
8580 if (ins(d
, "O_APPEND", (long)O_APPEND
)) return -1;
8583 if (ins(d
, "O_DSYNC", (long)O_DSYNC
)) return -1;
8586 if (ins(d
, "O_RSYNC", (long)O_RSYNC
)) return -1;
8589 if (ins(d
, "O_SYNC", (long)O_SYNC
)) return -1;
8592 if (ins(d
, "O_NOCTTY", (long)O_NOCTTY
)) return -1;
8595 if (ins(d
, "O_CREAT", (long)O_CREAT
)) return -1;
8598 if (ins(d
, "O_EXCL", (long)O_EXCL
)) return -1;
8601 if (ins(d
, "O_TRUNC", (long)O_TRUNC
)) return -1;
8604 if (ins(d
, "O_BINARY", (long)O_BINARY
)) return -1;
8607 if (ins(d
, "O_TEXT", (long)O_TEXT
)) return -1;
8610 if (ins(d
, "O_LARGEFILE", (long)O_LARGEFILE
)) return -1;
8613 if (ins(d
, "O_SHLOCK", (long)O_SHLOCK
)) return -1;
8616 if (ins(d
, "O_EXLOCK", (long)O_EXLOCK
)) return -1;
8621 /* Don't inherit in child processes. */
8622 if (ins(d
, "O_NOINHERIT", (long)O_NOINHERIT
)) return -1;
8624 #ifdef _O_SHORT_LIVED
8625 /* Optimize for short life (keep in memory). */
8626 /* MS forgot to define this one with a non-underscore form too. */
8627 if (ins(d
, "O_SHORT_LIVED", (long)_O_SHORT_LIVED
)) return -1;
8630 /* Automatically delete when last handle is closed. */
8631 if (ins(d
, "O_TEMPORARY", (long)O_TEMPORARY
)) return -1;
8634 /* Optimize for random access. */
8635 if (ins(d
, "O_RANDOM", (long)O_RANDOM
)) return -1;
8638 /* Optimize for sequential access. */
8639 if (ins(d
, "O_SEQUENTIAL", (long)O_SEQUENTIAL
)) return -1;
8642 /* GNU extensions. */
8644 /* Direct disk access. */
8645 if (ins(d
, "O_DIRECT", (long)O_DIRECT
)) return -1;
8648 /* Must be a directory. */
8649 if (ins(d
, "O_DIRECTORY", (long)O_DIRECTORY
)) return -1;
8652 /* Do not follow links. */
8653 if (ins(d
, "O_NOFOLLOW", (long)O_NOFOLLOW
)) return -1;
8656 /* These come from sysexits.h */
8658 if (ins(d
, "EX_OK", (long)EX_OK
)) return -1;
8661 if (ins(d
, "EX_USAGE", (long)EX_USAGE
)) return -1;
8662 #endif /* EX_USAGE */
8664 if (ins(d
, "EX_DATAERR", (long)EX_DATAERR
)) return -1;
8665 #endif /* EX_DATAERR */
8667 if (ins(d
, "EX_NOINPUT", (long)EX_NOINPUT
)) return -1;
8668 #endif /* EX_NOINPUT */
8670 if (ins(d
, "EX_NOUSER", (long)EX_NOUSER
)) return -1;
8671 #endif /* EX_NOUSER */
8673 if (ins(d
, "EX_NOHOST", (long)EX_NOHOST
)) return -1;
8674 #endif /* EX_NOHOST */
8675 #ifdef EX_UNAVAILABLE
8676 if (ins(d
, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE
)) return -1;
8677 #endif /* EX_UNAVAILABLE */
8679 if (ins(d
, "EX_SOFTWARE", (long)EX_SOFTWARE
)) return -1;
8680 #endif /* EX_SOFTWARE */
8682 if (ins(d
, "EX_OSERR", (long)EX_OSERR
)) return -1;
8683 #endif /* EX_OSERR */
8685 if (ins(d
, "EX_OSFILE", (long)EX_OSFILE
)) return -1;
8686 #endif /* EX_OSFILE */
8688 if (ins(d
, "EX_CANTCREAT", (long)EX_CANTCREAT
)) return -1;
8689 #endif /* EX_CANTCREAT */
8691 if (ins(d
, "EX_IOERR", (long)EX_IOERR
)) return -1;
8692 #endif /* EX_IOERR */
8694 if (ins(d
, "EX_TEMPFAIL", (long)EX_TEMPFAIL
)) return -1;
8695 #endif /* EX_TEMPFAIL */
8697 if (ins(d
, "EX_PROTOCOL", (long)EX_PROTOCOL
)) return -1;
8698 #endif /* EX_PROTOCOL */
8700 if (ins(d
, "EX_NOPERM", (long)EX_NOPERM
)) return -1;
8701 #endif /* EX_NOPERM */
8703 if (ins(d
, "EX_CONFIG", (long)EX_CONFIG
)) return -1;
8704 #endif /* EX_CONFIG */
8706 if (ins(d
, "EX_NOTFOUND", (long)EX_NOTFOUND
)) return -1;
8707 #endif /* EX_NOTFOUND */
8710 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8711 if (ins(d
, "P_WAIT", (long)P_WAIT
)) return -1;
8712 if (ins(d
, "P_NOWAIT", (long)P_NOWAIT
)) return -1;
8713 if (ins(d
, "P_OVERLAY", (long)P_OVERLAY
)) return -1;
8714 if (ins(d
, "P_DEBUG", (long)P_DEBUG
)) return -1;
8715 if (ins(d
, "P_SESSION", (long)P_SESSION
)) return -1;
8716 if (ins(d
, "P_DETACH", (long)P_DETACH
)) return -1;
8717 if (ins(d
, "P_PM", (long)P_PM
)) return -1;
8718 if (ins(d
, "P_DEFAULT", (long)P_DEFAULT
)) return -1;
8719 if (ins(d
, "P_MINIMIZE", (long)P_MINIMIZE
)) return -1;
8720 if (ins(d
, "P_MAXIMIZE", (long)P_MAXIMIZE
)) return -1;
8721 if (ins(d
, "P_FULLSCREEN", (long)P_FULLSCREEN
)) return -1;
8722 if (ins(d
, "P_WINDOWED", (long)P_WINDOWED
)) return -1;
8723 if (ins(d
, "P_FOREGROUND", (long)P_FOREGROUND
)) return -1;
8724 if (ins(d
, "P_BACKGROUND", (long)P_BACKGROUND
)) return -1;
8725 if (ins(d
, "P_NOCLOSE", (long)P_NOCLOSE
)) return -1;
8726 if (ins(d
, "P_NOSESSION", (long)P_NOSESSION
)) return -1;
8727 if (ins(d
, "P_QUOTE", (long)P_QUOTE
)) return -1;
8728 if (ins(d
, "P_TILDE", (long)P_TILDE
)) return -1;
8729 if (ins(d
, "P_UNRELATED", (long)P_UNRELATED
)) return -1;
8730 if (ins(d
, "P_DEBUGDESC", (long)P_DEBUGDESC
)) return -1;
8732 if (ins(d
, "P_WAIT", (long)_P_WAIT
)) return -1;
8733 if (ins(d
, "P_NOWAIT", (long)_P_NOWAIT
)) return -1;
8734 if (ins(d
, "P_OVERLAY", (long)_OLD_P_OVERLAY
)) return -1;
8735 if (ins(d
, "P_NOWAITO", (long)_P_NOWAITO
)) return -1;
8736 if (ins(d
, "P_DETACH", (long)_P_DETACH
)) return -1;
8740 #if defined(PYOS_OS2)
8741 if (insertvalues(d
)) return -1;
8747 #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__)
8748 #define INITFUNC initnt
8749 #define MODNAME "nt"
8751 #elif defined(PYOS_OS2)
8752 #define INITFUNC initos2
8753 #define MODNAME "os2"
8756 #define INITFUNC initposix
8757 #define MODNAME "posix"
8765 m
= Py_InitModule3(MODNAME
,
8771 /* Initialize environ dictionary */
8772 v
= convertenviron();
8774 if (v
== NULL
|| PyModule_AddObject(m
, "environ", v
) != 0)
8781 if (setup_confname_tables(m
))
8784 Py_INCREF(PyExc_OSError
);
8785 PyModule_AddObject(m
, "error", PyExc_OSError
);
8788 if (posix_putenv_garbage
== NULL
)
8789 posix_putenv_garbage
= PyDict_New();
8793 stat_result_desc
.name
= MODNAME
".stat_result";
8794 stat_result_desc
.fields
[7].name
= PyStructSequence_UnnamedField
;
8795 stat_result_desc
.fields
[8].name
= PyStructSequence_UnnamedField
;
8796 stat_result_desc
.fields
[9].name
= PyStructSequence_UnnamedField
;
8797 PyStructSequence_InitType(&StatResultType
, &stat_result_desc
);
8798 structseq_new
= StatResultType
.tp_new
;
8799 StatResultType
.tp_new
= statresult_new
;
8801 statvfs_result_desc
.name
= MODNAME
".statvfs_result";
8802 PyStructSequence_InitType(&StatVFSResultType
, &statvfs_result_desc
);
8804 Py_INCREF((PyObject
*) &StatResultType
);
8805 PyModule_AddObject(m
, "stat_result", (PyObject
*) &StatResultType
);
8806 Py_INCREF((PyObject
*) &StatVFSResultType
);
8807 PyModule_AddObject(m
, "statvfs_result",
8808 (PyObject
*) &StatVFSResultType
);
8813 * Step 2 of weak-linking support on Mac OS X.
8815 * The code below removes functions that are not available on the
8816 * currently active platform.
8818 * This block allow one to use a python binary that was build on
8819 * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
8822 #ifdef HAVE_FSTATVFS
8823 if (fstatvfs
== NULL
) {
8824 if (PyObject_DelAttrString(m
, "fstatvfs") == -1) {
8828 #endif /* HAVE_FSTATVFS */
8831 if (statvfs
== NULL
) {
8832 if (PyObject_DelAttrString(m
, "statvfs") == -1) {
8836 #endif /* HAVE_STATVFS */
8839 if (lchown
== NULL
) {
8840 if (PyObject_DelAttrString(m
, "lchown") == -1) {
8844 #endif /* HAVE_LCHOWN */
8847 #endif /* __APPLE__ */