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
);
195 extern int fchmod(int, mode_t);
198 extern int lchmod(const char *, mode_t);
200 extern int chown(const char *, uid_t
, gid_t
);
201 extern char *getcwd(char *, int);
202 extern char *strerror(int);
203 extern int link(const char *, const char *);
204 extern int rename(const char *, const char *);
205 extern int stat(const char *, struct stat
*);
206 extern int unlink(const char *);
207 extern int pclose(FILE *);
209 extern int symlink(const char *, const char *);
210 #endif /* HAVE_SYMLINK */
212 extern int lstat(const char *, struct stat
*);
213 #endif /* HAVE_LSTAT */
214 #endif /* !HAVE_UNISTD_H */
216 #endif /* !_MSC_VER */
220 #endif /* HAVE_UTIME_H */
222 #ifdef HAVE_SYS_UTIME_H
223 #include <sys/utime.h>
224 #define HAVE_UTIME_H /* pretend we do for the rest of this file */
225 #endif /* HAVE_SYS_UTIME_H */
227 #ifdef HAVE_SYS_TIMES_H
228 #include <sys/times.h>
229 #endif /* HAVE_SYS_TIMES_H */
231 #ifdef HAVE_SYS_PARAM_H
232 #include <sys/param.h>
233 #endif /* HAVE_SYS_PARAM_H */
235 #ifdef HAVE_SYS_UTSNAME_H
236 #include <sys/utsname.h>
237 #endif /* HAVE_SYS_UTSNAME_H */
241 #define NAMLEN(dirent) strlen((dirent)->d_name)
243 #if defined(__WATCOMC__) && !defined(__QNX__)
245 #define NAMLEN(dirent) strlen((dirent)->d_name)
247 #define dirent direct
248 #define NAMLEN(dirent) (dirent)->d_namlen
250 #ifdef HAVE_SYS_NDIR_H
251 #include <sys/ndir.h>
253 #ifdef HAVE_SYS_DIR_H
268 #ifdef HAVE_PROCESS_H
273 #include <shellapi.h> /* for ShellExecute() */
275 #define pclose _pclose
276 #endif /* _MSC_VER */
278 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
283 #if defined(PATH_MAX) && PATH_MAX > 1024
284 #define MAXPATHLEN PATH_MAX
286 #define MAXPATHLEN 1024
288 #endif /* MAXPATHLEN */
291 /* Emulate some macros on systems that have a union instead of macros */
294 #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
298 #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
302 #define WTERMSIG(u_wait) ((u_wait).w_termsig)
305 #define WAIT_TYPE union wait
306 #define WAIT_STATUS_INT(s) (s.w_status)
308 #else /* !UNION_WAIT */
309 #define WAIT_TYPE int
310 #define WAIT_STATUS_INT(s) (s)
311 #endif /* UNION_WAIT */
313 /* Don't use the "_r" form if we don't need it (also, won't have a
314 prototype for it, at least on Solaris -- maybe others as well?). */
315 #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
316 #define USE_CTERMID_R
319 #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
323 /* choose the appropriate stat and fstat functions and return structs */
325 #if defined(MS_WIN64) || defined(MS_WINDOWS)
326 # define STAT win32_stat
327 # define FSTAT win32_fstat
328 # define STRUCT_STAT struct win32_stat
332 # define STRUCT_STAT struct stat
335 #if defined(MAJOR_IN_MKDEV)
336 #include <sys/mkdev.h>
338 #if defined(MAJOR_IN_SYSMACROS)
339 #include <sys/sysmacros.h>
341 #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
342 #include <sys/mkdev.h>
346 /* Return a dictionary corresponding to the POSIX environment table */
347 #ifdef WITH_NEXT_FRAMEWORK
348 /* On Darwin/MacOSX a shared library or framework has no access to
349 ** environ directly, we must obtain it with _NSGetEnviron().
351 #include <crt_externs.h>
352 static char **environ
;
353 #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
354 extern char **environ
;
355 #endif /* !_MSC_VER */
365 #ifdef WITH_NEXT_FRAMEWORK
367 environ
= *_NSGetEnviron();
371 /* This part ignores errors */
372 for (e
= environ
; *e
!= NULL
; e
++) {
375 char *p
= strchr(*e
, '=');
378 k
= PyString_FromStringAndSize(*e
, (int)(p
-*e
));
383 v
= PyString_FromString(p
+1);
389 if (PyDict_GetItem(d
, k
) == NULL
) {
390 if (PyDict_SetItem(d
, k
, v
) != 0)
396 #if defined(PYOS_OS2)
399 char buffer
[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
401 rc
= DosQueryExtLIBPATH(buffer
, BEGIN_LIBPATH
);
402 if (rc
== NO_ERROR
) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
403 PyObject
*v
= PyString_FromString(buffer
);
404 PyDict_SetItemString(d
, "BEGINLIBPATH", v
);
407 rc
= DosQueryExtLIBPATH(buffer
, END_LIBPATH
);
408 if (rc
== NO_ERROR
) { /* (not a typo, envname is NOT 'END_LIBPATH') */
409 PyObject
*v
= PyString_FromString(buffer
);
410 PyDict_SetItemString(d
, "ENDLIBPATH", v
);
419 /* Set a POSIX-specific error from errno, and return NULL */
424 return PyErr_SetFromErrno(PyExc_OSError
);
427 posix_error_with_filename(char* name
)
429 return PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
432 #ifdef Py_WIN_WIDE_FILENAMES
434 posix_error_with_unicode_filename(Py_UNICODE
* name
)
436 return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError
, name
);
438 #endif /* Py_WIN_WIDE_FILENAMES */
442 posix_error_with_allocated_filename(char* name
)
444 PyObject
*rc
= PyErr_SetFromErrnoWithFilename(PyExc_OSError
, name
);
451 win32_error(char* function
, char* filename
)
453 /* XXX We should pass the function name along in the future.
454 (_winreg.c also wants to pass the function name.)
455 This would however require an additional param to the
456 Windows error object, which is non-trivial.
458 errno
= GetLastError();
460 return PyErr_SetFromWindowsErrWithFilename(errno
, filename
);
462 return PyErr_SetFromWindowsErr(errno
);
465 #ifdef Py_WIN_WIDE_FILENAMES
467 win32_error_unicode(char* function
, Py_UNICODE
* filename
)
469 /* XXX - see win32_error for comments on 'function' */
470 errno
= GetLastError();
472 return PyErr_SetFromWindowsErrWithUnicodeFilename(errno
, filename
);
474 return PyErr_SetFromWindowsErr(errno
);
478 convert_to_unicode(PyObject
**param
)
480 if (PyUnicode_CheckExact(*param
))
482 else if (PyUnicode_Check(*param
))
483 /* For a Unicode subtype that's not a Unicode object,
484 return a true Unicode object with the same data. */
485 *param
= PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param
),
486 PyUnicode_GET_SIZE(*param
));
488 *param
= PyUnicode_FromEncodedObject(*param
,
489 Py_FileSystemDefaultEncoding
,
491 return (*param
) != NULL
;
494 #endif /* Py_WIN_WIDE_FILENAMES */
498 #if defined(PYOS_OS2)
499 /**********************************************************************
500 * Helper Function to Trim and Format OS/2 Messages
501 **********************************************************************/
503 os2_formatmsg(char *msgbuf
, int msglen
, char *reason
)
505 msgbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
507 if (strlen(msgbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
508 char *lastc
= &msgbuf
[ strlen(msgbuf
)-1 ];
510 while (lastc
> msgbuf
&& isspace(Py_CHARMASK(*lastc
)))
511 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
514 /* Add Optional Reason Text */
516 strcat(msgbuf
, " : ");
517 strcat(msgbuf
, reason
);
521 /**********************************************************************
522 * Decode an OS/2 Operating System Error Code
524 * A convenience function to lookup an OS/2 error code and return a
525 * text message we can use to raise a Python exception.
528 * The messages for errors returned from the OS/2 kernel reside in
529 * the file OSO001.MSG in the \OS2 directory hierarchy.
531 **********************************************************************/
533 os2_strerror(char *msgbuf
, int msgbuflen
, int errorcode
, char *reason
)
538 /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
539 Py_BEGIN_ALLOW_THREADS
540 rc
= DosGetMessage(NULL
, 0, msgbuf
, msgbuflen
,
541 errorcode
, "oso001.msg", &msglen
);
545 os2_formatmsg(msgbuf
, msglen
, reason
);
547 PyOS_snprintf(msgbuf
, msgbuflen
,
548 "unknown OS error #%d", errorcode
);
553 /* Set an OS/2-specific error and return NULL. OS/2 kernel
554 errors are not in a global variable e.g. 'errno' nor are
555 they congruent with posix error numbers. */
557 static PyObject
* os2_error(int code
)
562 os2_strerror(text
, sizeof(text
), code
, "");
564 v
= Py_BuildValue("(is)", code
, text
);
566 PyErr_SetObject(PyExc_OSError
, v
);
569 return NULL
; /* Signal to Python that an Exception is Pending */
574 /* POSIX generic methods */
577 posix_fildes(PyObject
*fdobj
, int (*func
)(int))
581 fd
= PyObject_AsFileDescriptor(fdobj
);
584 Py_BEGIN_ALLOW_THREADS
588 return posix_error();
593 #ifdef Py_WIN_WIDE_FILENAMES
595 unicode_file_names(void)
597 static int canusewide
= -1;
598 if (canusewide
== -1) {
599 /* As per doc for ::GetVersion(), this is the correct test for
600 the Windows NT family. */
601 canusewide
= (GetVersion() < 0x80000000) ? 1 : 0;
608 posix_1str(PyObject
*args
, char *format
, int (*func
)(const char*))
612 if (!PyArg_ParseTuple(args
, format
,
613 Py_FileSystemDefaultEncoding
, &path1
))
615 Py_BEGIN_ALLOW_THREADS
616 res
= (*func
)(path1
);
619 return posix_error_with_allocated_filename(path1
);
626 posix_2str(PyObject
*args
,
628 int (*func
)(const char *, const char *))
630 char *path1
= NULL
, *path2
= NULL
;
632 if (!PyArg_ParseTuple(args
, format
,
633 Py_FileSystemDefaultEncoding
, &path1
,
634 Py_FileSystemDefaultEncoding
, &path2
))
636 Py_BEGIN_ALLOW_THREADS
637 res
= (*func
)(path1
, path2
);
642 /* XXX how to report both path1 and path2??? */
643 return posix_error();
648 #ifdef Py_WIN_WIDE_FILENAMES
650 win32_1str(PyObject
* args
, char* func
,
651 char* format
, BOOL (__stdcall
*funcA
)(LPCSTR
),
652 char* wformat
, BOOL (__stdcall
*funcW
)(LPWSTR
))
657 if (unicode_file_names()) {
658 if (!PyArg_ParseTuple(args
, wformat
, &uni
))
661 Py_BEGIN_ALLOW_THREADS
662 result
= funcW(PyUnicode_AsUnicode(uni
));
665 return win32_error_unicode(func
, PyUnicode_AsUnicode(uni
));
670 if (!PyArg_ParseTuple(args
, format
, &ansi
))
672 Py_BEGIN_ALLOW_THREADS
673 result
= funcA(ansi
);
676 return win32_error(func
, ansi
);
682 /* This is a reimplementation of the C library's chdir function,
683 but one that produces Win32 errors instead of DOS error codes.
684 chdir is essentially a wrapper around SetCurrentDirectory; however,
685 it also needs to set "magic" environment variables indicating
686 the per-drive current directory, which are of the form =<drive>: */
687 static BOOL __stdcall
688 win32_chdir(LPCSTR path
)
690 char new_path
[MAX_PATH
+1];
694 if(!SetCurrentDirectoryA(path
))
696 result
= GetCurrentDirectoryA(MAX_PATH
+1, new_path
);
699 /* In the ANSI API, there should not be any paths longer
701 assert(result
<= MAX_PATH
+1);
702 if (strncmp(new_path
, "\\\\", 2) == 0 ||
703 strncmp(new_path
, "//", 2) == 0)
704 /* UNC path, nothing to do. */
706 env
[1] = new_path
[0];
707 return SetEnvironmentVariableA(env
, new_path
);
710 /* The Unicode version differs from the ANSI version
711 since the current directory might exceed MAX_PATH characters */
712 static BOOL __stdcall
713 win32_wchdir(LPCWSTR path
)
715 wchar_t _new_path
[MAX_PATH
+1], *new_path
= _new_path
;
717 wchar_t env
[4] = L
"=x:";
719 if(!SetCurrentDirectoryW(path
))
721 result
= GetCurrentDirectoryW(MAX_PATH
+1, new_path
);
724 if (result
> MAX_PATH
+1) {
725 new_path
= malloc(result
* sizeof(wchar_t));
727 SetLastError(ERROR_OUTOFMEMORY
);
730 result
= GetCurrentDirectoryW(result
, new_path
);
736 if (wcsncmp(new_path
, L
"\\\\", 2) == 0 ||
737 wcsncmp(new_path
, L
"//", 2) == 0)
738 /* UNC path, nothing to do. */
740 env
[1] = new_path
[0];
741 result
= SetEnvironmentVariableW(env
, new_path
);
742 if (new_path
!= _new_path
)
749 /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
750 - time stamps are restricted to second resolution
751 - file modification times suffer from forth-and-back conversions between
753 Therefore, we implement our own stat, based on the Win32 API directly.
755 #define HAVE_STAT_NSEC 1
760 unsigned short st_mode
;
774 static __int64 secs_between_epochs
= 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
777 FILE_TIME_to_time_t_nsec(FILETIME
*in_ptr
, int *time_out
, int* nsec_out
)
779 /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
780 /* Cannot simply cast and dereference in_ptr,
781 since it might not be aligned properly */
783 memcpy(&in
, in_ptr
, sizeof(in
));
784 *nsec_out
= (int)(in
% 10000000) * 100; /* FILETIME is in units of 100 nsec. */
785 /* XXX Win32 supports time stamps past 2038; we currently don't */
786 *time_out
= Py_SAFE_DOWNCAST((in
/ 10000000) - secs_between_epochs
, __int64
, int);
790 time_t_to_FILE_TIME(int time_in
, int nsec_in
, FILETIME
*out_ptr
)
794 out
= time_in
+ secs_between_epochs
;
795 out
= out
* 10000000 + nsec_in
/ 100;
796 memcpy(out_ptr
, &out
, sizeof(out
));
799 /* Below, we *know* that ugo+r is 0444 */
801 #error Unsupported C library
804 attributes_to_mode(DWORD attr
)
807 if (attr
& FILE_ATTRIBUTE_DIRECTORY
)
808 m
|= _S_IFDIR
| 0111; /* IFEXEC for user,group,other */
811 if (attr
& FILE_ATTRIBUTE_READONLY
)
819 attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA
*info
, struct win32_stat
*result
)
821 memset(result
, 0, sizeof(*result
));
822 result
->st_mode
= attributes_to_mode(info
->dwFileAttributes
);
823 result
->st_size
= (((__int64
)info
->nFileSizeHigh
)<<32) + info
->nFileSizeLow
;
824 FILE_TIME_to_time_t_nsec(&info
->ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
825 FILE_TIME_to_time_t_nsec(&info
->ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
826 FILE_TIME_to_time_t_nsec(&info
->ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
831 /* Emulate GetFileAttributesEx[AW] on Windows 95 */
832 static int checked
= 0;
833 static BOOL (CALLBACK
*gfaxa
)(LPCSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
834 static BOOL (CALLBACK
*gfaxw
)(LPCWSTR
, GET_FILEEX_INFO_LEVELS
, LPVOID
);
842 hKernel32
= GetModuleHandle("KERNEL32");
843 *(FARPROC
*)&gfaxa
= GetProcAddress(hKernel32
, "GetFileAttributesExA");
844 *(FARPROC
*)&gfaxw
= GetProcAddress(hKernel32
, "GetFileAttributesExW");
848 attributes_from_dir(LPCSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
851 WIN32_FIND_DATAA FileData
;
852 hFindFile
= FindFirstFileA(pszFile
, &FileData
);
853 if (hFindFile
== INVALID_HANDLE_VALUE
)
855 FindClose(hFindFile
);
856 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
857 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
858 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
859 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
860 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
861 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
866 attributes_from_dir_w(LPCWSTR pszFile
, LPWIN32_FILE_ATTRIBUTE_DATA pfad
)
869 WIN32_FIND_DATAW FileData
;
870 hFindFile
= FindFirstFileW(pszFile
, &FileData
);
871 if (hFindFile
== INVALID_HANDLE_VALUE
)
873 FindClose(hFindFile
);
874 pfad
->dwFileAttributes
= FileData
.dwFileAttributes
;
875 pfad
->ftCreationTime
= FileData
.ftCreationTime
;
876 pfad
->ftLastAccessTime
= FileData
.ftLastAccessTime
;
877 pfad
->ftLastWriteTime
= FileData
.ftLastWriteTime
;
878 pfad
->nFileSizeHigh
= FileData
.nFileSizeHigh
;
879 pfad
->nFileSizeLow
= FileData
.nFileSizeLow
;
884 Py_GetFileAttributesExA(LPCSTR pszFile
,
885 GET_FILEEX_INFO_LEVELS level
,
889 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
890 /* First try to use the system's implementation, if that is
891 available and either succeeds to gives an error other than
892 that it isn't implemented. */
895 result
= gfaxa(pszFile
, level
, pv
);
896 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
899 /* It's either not present, or not implemented.
900 Emulate using FindFirstFile. */
901 if (level
!= GetFileExInfoStandard
) {
902 SetLastError(ERROR_INVALID_PARAMETER
);
905 /* Use GetFileAttributes to validate that the file name
906 does not contain wildcards (which FindFirstFile would
908 if (GetFileAttributesA(pszFile
) == 0xFFFFFFFF)
910 return attributes_from_dir(pszFile
, pfad
);
914 Py_GetFileAttributesExW(LPCWSTR pszFile
,
915 GET_FILEEX_INFO_LEVELS level
,
919 LPWIN32_FILE_ATTRIBUTE_DATA pfad
= pv
;
920 /* First try to use the system's implementation, if that is
921 available and either succeeds to gives an error other than
922 that it isn't implemented. */
925 result
= gfaxw(pszFile
, level
, pv
);
926 if (result
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
929 /* It's either not present, or not implemented.
930 Emulate using FindFirstFile. */
931 if (level
!= GetFileExInfoStandard
) {
932 SetLastError(ERROR_INVALID_PARAMETER
);
935 /* Use GetFileAttributes to validate that the file name
936 does not contain wildcards (which FindFirstFile would
938 if (GetFileAttributesW(pszFile
) == 0xFFFFFFFF)
940 return attributes_from_dir_w(pszFile
, pfad
);
944 win32_stat(const char* path
, struct win32_stat
*result
)
946 WIN32_FILE_ATTRIBUTE_DATA info
;
949 /* XXX not supported on Win95 and NT 3.x */
950 if (!Py_GetFileAttributesExA(path
, GetFileExInfoStandard
, &info
)) {
951 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
952 /* Protocol violation: we explicitly clear errno, instead of
953 setting it to a POSIX error. Callers should use GetLastError. */
957 /* Could not get attributes on open file. Fall back to
958 reading the directory. */
959 if (!attributes_from_dir(path
, &info
)) {
960 /* Very strange. This should not fail now */
966 code
= attribute_data_to_stat(&info
, result
);
969 /* Set S_IFEXEC if it is an .exe, .bat, ... */
970 dot
= strrchr(path
, '.');
972 if (stricmp(dot
, ".bat") == 0 ||
973 stricmp(dot
, ".cmd") == 0 ||
974 stricmp(dot
, ".exe") == 0 ||
975 stricmp(dot
, ".com") == 0)
976 result
->st_mode
|= 0111;
982 win32_wstat(const wchar_t* path
, struct win32_stat
*result
)
986 WIN32_FILE_ATTRIBUTE_DATA info
;
987 /* XXX not supported on Win95 and NT 3.x */
988 if (!Py_GetFileAttributesExW(path
, GetFileExInfoStandard
, &info
)) {
989 if (GetLastError() != ERROR_SHARING_VIOLATION
) {
990 /* Protocol violation: we explicitly clear errno, instead of
991 setting it to a POSIX error. Callers should use GetLastError. */
995 /* Could not get attributes on open file. Fall back to
996 reading the directory. */
997 if (!attributes_from_dir_w(path
, &info
)) {
998 /* Very strange. This should not fail now */
1004 code
= attribute_data_to_stat(&info
, result
);
1007 /* Set IFEXEC if it is an .exe, .bat, ... */
1008 dot
= wcsrchr(path
, '.');
1010 if (_wcsicmp(dot
, L
".bat") == 0 ||
1011 _wcsicmp(dot
, L
".cmd") == 0 ||
1012 _wcsicmp(dot
, L
".exe") == 0 ||
1013 _wcsicmp(dot
, L
".com") == 0)
1014 result
->st_mode
|= 0111;
1020 win32_fstat(int file_number
, struct win32_stat
*result
)
1022 BY_HANDLE_FILE_INFORMATION info
;
1026 h
= (HANDLE
)_get_osfhandle(file_number
);
1028 /* Protocol violation: we explicitly clear errno, instead of
1029 setting it to a POSIX error. Callers should use GetLastError. */
1032 if (h
== INVALID_HANDLE_VALUE
) {
1033 /* This is really a C library error (invalid file handle).
1034 We set the Win32 error to the closes one matching. */
1035 SetLastError(ERROR_INVALID_HANDLE
);
1038 memset(result
, 0, sizeof(*result
));
1040 type
= GetFileType(h
);
1041 if (type
== FILE_TYPE_UNKNOWN
) {
1042 DWORD error
= GetLastError();
1046 /* else: valid but unknown file */
1049 if (type
!= FILE_TYPE_DISK
) {
1050 if (type
== FILE_TYPE_CHAR
)
1051 result
->st_mode
= _S_IFCHR
;
1052 else if (type
== FILE_TYPE_PIPE
)
1053 result
->st_mode
= _S_IFIFO
;
1057 if (!GetFileInformationByHandle(h
, &info
)) {
1061 /* similar to stat() */
1062 result
->st_mode
= attributes_to_mode(info
.dwFileAttributes
);
1063 result
->st_size
= (((__int64
)info
.nFileSizeHigh
)<<32) + info
.nFileSizeLow
;
1064 FILE_TIME_to_time_t_nsec(&info
.ftCreationTime
, &result
->st_ctime
, &result
->st_ctime_nsec
);
1065 FILE_TIME_to_time_t_nsec(&info
.ftLastWriteTime
, &result
->st_mtime
, &result
->st_mtime_nsec
);
1066 FILE_TIME_to_time_t_nsec(&info
.ftLastAccessTime
, &result
->st_atime
, &result
->st_atime_nsec
);
1067 /* specific to fstat() */
1068 result
->st_nlink
= info
.nNumberOfLinks
;
1069 result
->st_ino
= (((__int64
)info
.nFileIndexHigh
)<<32) + info
.nFileIndexLow
;
1073 #endif /* MS_WINDOWS */
1075 PyDoc_STRVAR(stat_result__doc__
,
1076 "stat_result: Result from stat or lstat.\n\n\
1077 This object may be accessed either as a tuple of\n\
1078 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
1079 or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1081 Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1082 or st_flags, they are available as attributes only.\n\
1084 See os.stat for more information.");
1086 static PyStructSequence_Field stat_result_fields
[] = {
1087 {"st_mode", "protection bits"},
1088 {"st_ino", "inode"},
1089 {"st_dev", "device"},
1090 {"st_nlink", "number of hard links"},
1091 {"st_uid", "user ID of owner"},
1092 {"st_gid", "group ID of owner"},
1093 {"st_size", "total size, in bytes"},
1094 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1095 {NULL
, "integer time of last access"},
1096 {NULL
, "integer time of last modification"},
1097 {NULL
, "integer time of last change"},
1098 {"st_atime", "time of last access"},
1099 {"st_mtime", "time of last modification"},
1100 {"st_ctime", "time of last change"},
1101 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1102 {"st_blksize", "blocksize for filesystem I/O"},
1104 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1105 {"st_blocks", "number of blocks allocated"},
1107 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1108 {"st_rdev", "device type (if inode device)"},
1110 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1111 {"st_flags", "user defined flags for file"},
1113 #ifdef HAVE_STRUCT_STAT_ST_GEN
1114 {"st_gen", "generation number"},
1116 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1117 {"st_birthtime", "time of creation"},
1122 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1123 #define ST_BLKSIZE_IDX 13
1125 #define ST_BLKSIZE_IDX 12
1128 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1129 #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1131 #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1134 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1135 #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1137 #define ST_RDEV_IDX ST_BLOCKS_IDX
1140 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1141 #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1143 #define ST_FLAGS_IDX ST_RDEV_IDX
1146 #ifdef HAVE_STRUCT_STAT_ST_GEN
1147 #define ST_GEN_IDX (ST_FLAGS_IDX+1)
1149 #define ST_GEN_IDX ST_FLAGS_IDX
1152 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1153 #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1155 #define ST_BIRTHTIME_IDX ST_GEN_IDX
1158 static PyStructSequence_Desc stat_result_desc
= {
1159 "stat_result", /* name */
1160 stat_result__doc__
, /* doc */
1165 PyDoc_STRVAR(statvfs_result__doc__
,
1166 "statvfs_result: Result from statvfs or fstatvfs.\n\n\
1167 This object may be accessed either as a tuple of\n\
1168 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
1169 or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
1171 See os.statvfs for more information.");
1173 static PyStructSequence_Field statvfs_result_fields
[] = {
1187 static PyStructSequence_Desc statvfs_result_desc
= {
1188 "statvfs_result", /* name */
1189 statvfs_result__doc__
, /* doc */
1190 statvfs_result_fields
,
1194 static int initialized
;
1195 static PyTypeObject StatResultType
;
1196 static PyTypeObject StatVFSResultType
;
1197 static newfunc structseq_new
;
1200 statresult_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1202 PyStructSequence
*result
;
1205 result
= (PyStructSequence
*)structseq_new(type
, args
, kwds
);
1208 /* If we have been initialized from a tuple,
1209 st_?time might be set to None. Initialize it
1210 from the int slots. */
1211 for (i
= 7; i
<= 9; i
++) {
1212 if (result
->ob_item
[i
+3] == Py_None
) {
1214 Py_INCREF(result
->ob_item
[i
]);
1215 result
->ob_item
[i
+3] = result
->ob_item
[i
];
1218 return (PyObject
*)result
;
1223 /* If true, st_?time is float. */
1224 static int _stat_float_times
= 1;
1226 PyDoc_STRVAR(stat_float_times__doc__
,
1227 "stat_float_times([newval]) -> oldval\n\n\
1228 Determine whether os.[lf]stat represents time stamps as float objects.\n\
1229 If newval is True, future calls to stat() return floats, if it is False,\n\
1230 future calls return ints. \n\
1231 If newval is omitted, return the current setting.\n");
1234 stat_float_times(PyObject
* self
, PyObject
*args
)
1237 if (!PyArg_ParseTuple(args
, "|i:stat_float_times", &newval
))
1240 /* Return old value */
1241 return PyBool_FromLong(_stat_float_times
);
1242 _stat_float_times
= newval
;
1248 fill_time(PyObject
*v
, int index
, time_t sec
, unsigned long nsec
)
1250 PyObject
*fval
,*ival
;
1251 #if SIZEOF_TIME_T > SIZEOF_LONG
1252 ival
= PyLong_FromLongLong((PY_LONG_LONG
)sec
);
1254 ival
= PyInt_FromLong((long)sec
);
1258 if (_stat_float_times
) {
1259 fval
= PyFloat_FromDouble(sec
+ 1e-9*nsec
);
1264 PyStructSequence_SET_ITEM(v
, index
, ival
);
1265 PyStructSequence_SET_ITEM(v
, index
+3, fval
);
1268 /* pack a system stat C structure into the Python stat tuple
1269 (used by posix_stat() and posix_fstat()) */
1271 _pystat_fromstructstat(STRUCT_STAT
*st
)
1273 unsigned long ansec
, mnsec
, cnsec
;
1274 PyObject
*v
= PyStructSequence_New(&StatResultType
);
1278 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long)st
->st_mode
));
1279 #ifdef HAVE_LARGEFILE_SUPPORT
1280 PyStructSequence_SET_ITEM(v
, 1,
1281 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_ino
));
1283 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long)st
->st_ino
));
1285 #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
1286 PyStructSequence_SET_ITEM(v
, 2,
1287 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_dev
));
1289 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long)st
->st_dev
));
1291 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long)st
->st_nlink
));
1292 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long)st
->st_uid
));
1293 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long)st
->st_gid
));
1294 #ifdef HAVE_LARGEFILE_SUPPORT
1295 PyStructSequence_SET_ITEM(v
, 6,
1296 PyLong_FromLongLong((PY_LONG_LONG
)st
->st_size
));
1298 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong(st
->st_size
));
1301 #if defined(HAVE_STAT_TV_NSEC)
1302 ansec
= st
->st_atim
.tv_nsec
;
1303 mnsec
= st
->st_mtim
.tv_nsec
;
1304 cnsec
= st
->st_ctim
.tv_nsec
;
1305 #elif defined(HAVE_STAT_TV_NSEC2)
1306 ansec
= st
->st_atimespec
.tv_nsec
;
1307 mnsec
= st
->st_mtimespec
.tv_nsec
;
1308 cnsec
= st
->st_ctimespec
.tv_nsec
;
1309 #elif defined(HAVE_STAT_NSEC)
1310 ansec
= st
->st_atime_nsec
;
1311 mnsec
= st
->st_mtime_nsec
;
1312 cnsec
= st
->st_ctime_nsec
;
1314 ansec
= mnsec
= cnsec
= 0;
1316 fill_time(v
, 7, st
->st_atime
, ansec
);
1317 fill_time(v
, 8, st
->st_mtime
, mnsec
);
1318 fill_time(v
, 9, st
->st_ctime
, cnsec
);
1320 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1321 PyStructSequence_SET_ITEM(v
, ST_BLKSIZE_IDX
,
1322 PyInt_FromLong((long)st
->st_blksize
));
1324 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1325 PyStructSequence_SET_ITEM(v
, ST_BLOCKS_IDX
,
1326 PyInt_FromLong((long)st
->st_blocks
));
1328 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1329 PyStructSequence_SET_ITEM(v
, ST_RDEV_IDX
,
1330 PyInt_FromLong((long)st
->st_rdev
));
1332 #ifdef HAVE_STRUCT_STAT_ST_GEN
1333 PyStructSequence_SET_ITEM(v
, ST_GEN_IDX
,
1334 PyInt_FromLong((long)st
->st_gen
));
1336 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1339 unsigned long bsec
,bnsec
;
1340 bsec
= (long)st
->st_birthtime
;
1341 #ifdef HAVE_STAT_TV_NSEC2
1342 bnsec
= st
->st_birthtimespec
.tv_nsec
;
1346 if (_stat_float_times
) {
1347 val
= PyFloat_FromDouble(bsec
+ 1e-9*bnsec
);
1349 val
= PyInt_FromLong((long)bsec
);
1351 PyStructSequence_SET_ITEM(v
, ST_BIRTHTIME_IDX
,
1355 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
1356 PyStructSequence_SET_ITEM(v
, ST_FLAGS_IDX
,
1357 PyInt_FromLong((long)st
->st_flags
));
1360 if (PyErr_Occurred()) {
1370 /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
1371 where / can be used in place of \ and the trailing slash is optional.
1372 Both SERVER and SHARE must have at least one character.
1375 #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
1376 #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
1378 #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
1382 IsUNCRootA(char *path
, int pathlen
)
1384 #define ISSLASH ISSLASHA
1388 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1389 /* minimum UNCRoot is \\x\y */
1391 for (i
= 2; i
< pathlen
; i
++)
1392 if (ISSLASH(path
[i
])) break;
1393 if (i
== 2 || i
== pathlen
)
1394 /* do not allow \\\SHARE or \\SERVER */
1397 for (i
= share
; i
< pathlen
; i
++)
1398 if (ISSLASH(path
[i
])) break;
1399 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1404 #ifdef Py_WIN_WIDE_FILENAMES
1406 IsUNCRootW(Py_UNICODE
*path
, int pathlen
)
1408 #define ISSLASH ISSLASHW
1412 if (pathlen
< 5 || !ISSLASH(path
[0]) || !ISSLASH(path
[1]))
1413 /* minimum UNCRoot is \\x\y */
1415 for (i
= 2; i
< pathlen
; i
++)
1416 if (ISSLASH(path
[i
])) break;
1417 if (i
== 2 || i
== pathlen
)
1418 /* do not allow \\\SHARE or \\SERVER */
1421 for (i
= share
; i
< pathlen
; i
++)
1422 if (ISSLASH(path
[i
])) break;
1423 return (i
!= share
&& (i
== pathlen
|| i
== pathlen
-1));
1427 #endif /* Py_WIN_WIDE_FILENAMES */
1428 #endif /* MS_WINDOWS */
1431 posix_do_stat(PyObject
*self
, PyObject
*args
,
1434 int (*statfunc
)(const char *, STRUCT_STAT
*, ...),
1436 int (*statfunc
)(const char *, STRUCT_STAT
*),
1439 int (*wstatfunc
)(const Py_UNICODE
*, STRUCT_STAT
*))
1442 char *path
= NULL
; /* pass this to stat; do not free() it */
1443 char *pathfree
= NULL
; /* this memory must be free'd */
1447 #ifdef Py_WIN_WIDE_FILENAMES
1448 /* If on wide-character-capable OS see if argument
1449 is Unicode and if so use wide API. */
1450 if (unicode_file_names()) {
1451 PyUnicodeObject
*po
;
1452 if (PyArg_ParseTuple(args
, wformat
, &po
)) {
1453 Py_UNICODE
*wpath
= PyUnicode_AS_UNICODE(po
);
1455 Py_BEGIN_ALLOW_THREADS
1456 /* PyUnicode_AS_UNICODE result OK without
1457 thread lock as it is a simple dereference. */
1458 res
= wstatfunc(wpath
, &st
);
1459 Py_END_ALLOW_THREADS
1462 return win32_error_unicode("stat", wpath
);
1463 return _pystat_fromstructstat(&st
);
1465 /* Drop the argument parsing error as narrow strings
1471 if (!PyArg_ParseTuple(args
, format
,
1472 Py_FileSystemDefaultEncoding
, &path
))
1476 Py_BEGIN_ALLOW_THREADS
1477 res
= (*statfunc
)(path
, &st
);
1478 Py_END_ALLOW_THREADS
1482 result
= win32_error("stat", pathfree
);
1484 result
= posix_error_with_filename(pathfree
);
1488 result
= _pystat_fromstructstat(&st
);
1490 PyMem_Free(pathfree
);
1496 PyDoc_STRVAR(posix_access__doc__
,
1497 "access(path, mode) -> True if granted, False otherwise\n\n\
1498 Use the real uid/gid to test for access to a path. Note that most\n\
1499 operations will use the effective uid/gid, therefore this routine can\n\
1500 be used in a suid/sgid environment to test if the invoking user has the\n\
1501 specified access to the path. The mode argument can be F_OK to test\n\
1502 existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
1505 posix_access(PyObject
*self
, PyObject
*args
)
1510 #ifdef Py_WIN_WIDE_FILENAMES
1512 if (unicode_file_names()) {
1513 PyUnicodeObject
*po
;
1514 if (PyArg_ParseTuple(args
, "Ui:access", &po
, &mode
)) {
1515 Py_BEGIN_ALLOW_THREADS
1516 /* PyUnicode_AS_UNICODE OK without thread lock as
1517 it is a simple dereference. */
1518 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1519 Py_END_ALLOW_THREADS
1522 /* Drop the argument parsing error as narrow strings
1526 if (!PyArg_ParseTuple(args
, "eti:access",
1527 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1529 Py_BEGIN_ALLOW_THREADS
1530 attr
= GetFileAttributesA(path
);
1531 Py_END_ALLOW_THREADS
1534 if (attr
== 0xFFFFFFFF)
1535 /* File does not exist, or cannot read attributes */
1536 return PyBool_FromLong(0);
1537 /* Access is possible if either write access wasn't requested, or
1538 the file isn't read-only, or if it's a directory, as there are
1539 no read-only directories on Windows. */
1540 return PyBool_FromLong(!(mode
& 2)
1541 || !(attr
& FILE_ATTRIBUTE_READONLY
)
1542 || (attr
& FILE_ATTRIBUTE_DIRECTORY
));
1545 if (!PyArg_ParseTuple(args
, "eti:access",
1546 Py_FileSystemDefaultEncoding
, &path
, &mode
))
1548 Py_BEGIN_ALLOW_THREADS
1549 res
= access(path
, mode
);
1550 Py_END_ALLOW_THREADS
1552 return PyBool_FromLong(res
== 0);
1570 PyDoc_STRVAR(posix_ttyname__doc__
,
1571 "ttyname(fd) -> string\n\n\
1572 Return the name of the terminal device connected to 'fd'.");
1575 posix_ttyname(PyObject
*self
, PyObject
*args
)
1580 if (!PyArg_ParseTuple(args
, "i:ttyname", &id
))
1584 /* file descriptor 0 only, the default input device (stdin) */
1595 return posix_error();
1596 return PyString_FromString(ret
);
1601 PyDoc_STRVAR(posix_ctermid__doc__
,
1602 "ctermid() -> string\n\n\
1603 Return the name of the controlling terminal for this process.");
1606 posix_ctermid(PyObject
*self
, PyObject
*noargs
)
1609 char buffer
[L_ctermid
];
1611 #ifdef USE_CTERMID_R
1612 ret
= ctermid_r(buffer
);
1614 ret
= ctermid(buffer
);
1617 return posix_error();
1618 return PyString_FromString(buffer
);
1622 PyDoc_STRVAR(posix_chdir__doc__
,
1624 Change the current working directory to the specified path.");
1627 posix_chdir(PyObject
*self
, PyObject
*args
)
1630 return win32_1str(args
, "chdir", "s:chdir", win32_chdir
, "U:chdir", win32_wchdir
);
1631 #elif defined(PYOS_OS2) && defined(PYCC_GCC)
1632 return posix_1str(args
, "et:chdir", _chdir2
);
1633 #elif defined(__VMS)
1634 return posix_1str(args
, "et:chdir", (int (*)(const char *))chdir
);
1636 return posix_1str(args
, "et:chdir", chdir
);
1641 PyDoc_STRVAR(posix_fchdir__doc__
,
1642 "fchdir(fildes)\n\n\
1643 Change to the directory of the given file descriptor. fildes must be\n\
1644 opened on a directory, not a file.");
1647 posix_fchdir(PyObject
*self
, PyObject
*fdobj
)
1649 return posix_fildes(fdobj
, fchdir
);
1651 #endif /* HAVE_FCHDIR */
1654 PyDoc_STRVAR(posix_chmod__doc__
,
1655 "chmod(path, mode)\n\n\
1656 Change the access permissions of a file.");
1659 posix_chmod(PyObject
*self
, PyObject
*args
)
1664 #ifdef Py_WIN_WIDE_FILENAMES
1666 if (unicode_file_names()) {
1667 PyUnicodeObject
*po
;
1668 if (PyArg_ParseTuple(args
, "Ui|:chmod", &po
, &i
)) {
1669 Py_BEGIN_ALLOW_THREADS
1670 attr
= GetFileAttributesW(PyUnicode_AS_UNICODE(po
));
1671 if (attr
!= 0xFFFFFFFF) {
1673 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1675 attr
|= FILE_ATTRIBUTE_READONLY
;
1676 res
= SetFileAttributesW(PyUnicode_AS_UNICODE(po
), attr
);
1680 Py_END_ALLOW_THREADS
1682 return win32_error_unicode("chmod",
1683 PyUnicode_AS_UNICODE(po
));
1687 /* Drop the argument parsing error as narrow strings
1691 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1694 Py_BEGIN_ALLOW_THREADS
1695 attr
= GetFileAttributesA(path
);
1696 if (attr
!= 0xFFFFFFFF) {
1698 attr
&= ~FILE_ATTRIBUTE_READONLY
;
1700 attr
|= FILE_ATTRIBUTE_READONLY
;
1701 res
= SetFileAttributesA(path
, attr
);
1705 Py_END_ALLOW_THREADS
1707 win32_error("chmod", path
);
1714 #else /* Py_WIN_WIDE_FILENAMES */
1715 if (!PyArg_ParseTuple(args
, "eti:chmod", Py_FileSystemDefaultEncoding
,
1718 Py_BEGIN_ALLOW_THREADS
1719 res
= chmod(path
, i
);
1720 Py_END_ALLOW_THREADS
1722 return posix_error_with_allocated_filename(path
);
1730 PyDoc_STRVAR(posix_fchmod__doc__
,
1731 "fchmod(fd, mode)\n\n\
1732 Change the access permissions of the file given by file\n\
1736 posix_fchmod(PyObject
*self
, PyObject
*args
)
1739 if (!PyArg_ParseTuple(args
, "ii:fchmod", &fd
, &mode
))
1741 Py_BEGIN_ALLOW_THREADS
1742 res
= fchmod(fd
, mode
);
1743 Py_END_ALLOW_THREADS
1745 return posix_error();
1748 #endif /* HAVE_FCHMOD */
1751 PyDoc_STRVAR(posix_lchmod__doc__
,
1752 "lchmod(path, mode)\n\n\
1753 Change the access permissions of a file. If path is a symlink, this\n\
1754 affects the link itself rather than the target.");
1757 posix_lchmod(PyObject
*self
, PyObject
*args
)
1762 if (!PyArg_ParseTuple(args
, "eti:lchmod", Py_FileSystemDefaultEncoding
,
1765 Py_BEGIN_ALLOW_THREADS
1766 res
= lchmod(path
, i
);
1767 Py_END_ALLOW_THREADS
1769 return posix_error_with_allocated_filename(path
);
1773 #endif /* HAVE_LCHMOD */
1777 PyDoc_STRVAR(posix_chflags__doc__
,
1778 "chflags(path, flags)\n\n\
1782 posix_chflags(PyObject
*self
, PyObject
*args
)
1785 unsigned long flags
;
1787 if (!PyArg_ParseTuple(args
, "etk:chflags",
1788 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1790 Py_BEGIN_ALLOW_THREADS
1791 res
= chflags(path
, flags
);
1792 Py_END_ALLOW_THREADS
1794 return posix_error_with_allocated_filename(path
);
1799 #endif /* HAVE_CHFLAGS */
1801 #ifdef HAVE_LCHFLAGS
1802 PyDoc_STRVAR(posix_lchflags__doc__
,
1803 "lchflags(path, flags)\n\n\
1805 This function will not follow symbolic links.");
1808 posix_lchflags(PyObject
*self
, PyObject
*args
)
1811 unsigned long flags
;
1813 if (!PyArg_ParseTuple(args
, "etk:lchflags",
1814 Py_FileSystemDefaultEncoding
, &path
, &flags
))
1816 Py_BEGIN_ALLOW_THREADS
1817 res
= lchflags(path
, flags
);
1818 Py_END_ALLOW_THREADS
1820 return posix_error_with_allocated_filename(path
);
1825 #endif /* HAVE_LCHFLAGS */
1828 PyDoc_STRVAR(posix_chroot__doc__
,
1830 Change root directory to path.");
1833 posix_chroot(PyObject
*self
, PyObject
*args
)
1835 return posix_1str(args
, "et:chroot", chroot
);
1840 PyDoc_STRVAR(posix_fsync__doc__
,
1842 force write of file with filedescriptor to disk.");
1845 posix_fsync(PyObject
*self
, PyObject
*fdobj
)
1847 return posix_fildes(fdobj
, fsync
);
1849 #endif /* HAVE_FSYNC */
1851 #ifdef HAVE_FDATASYNC
1854 extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
1857 PyDoc_STRVAR(posix_fdatasync__doc__
,
1858 "fdatasync(fildes)\n\n\
1859 force write of file with filedescriptor to disk.\n\
1860 does not force update of metadata.");
1863 posix_fdatasync(PyObject
*self
, PyObject
*fdobj
)
1865 return posix_fildes(fdobj
, fdatasync
);
1867 #endif /* HAVE_FDATASYNC */
1871 PyDoc_STRVAR(posix_chown__doc__
,
1872 "chown(path, uid, gid)\n\n\
1873 Change the owner and group id of path to the numeric uid and gid.");
1876 posix_chown(PyObject
*self
, PyObject
*args
)
1881 if (!PyArg_ParseTuple(args
, "etll:chown",
1882 Py_FileSystemDefaultEncoding
, &path
,
1885 Py_BEGIN_ALLOW_THREADS
1886 res
= chown(path
, (uid_t
) uid
, (gid_t
) gid
);
1887 Py_END_ALLOW_THREADS
1889 return posix_error_with_allocated_filename(path
);
1894 #endif /* HAVE_CHOWN */
1897 PyDoc_STRVAR(posix_fchown__doc__
,
1898 "fchown(fd, uid, gid)\n\n\
1899 Change the owner and group id of the file given by file descriptor\n\
1900 fd to the numeric uid and gid.");
1903 posix_fchown(PyObject
*self
, PyObject
*args
)
1907 if (!PyArg_ParseTuple(args
, "iii:chown", &fd
, &uid
, &gid
))
1909 Py_BEGIN_ALLOW_THREADS
1910 res
= fchown(fd
, (uid_t
) uid
, (gid_t
) gid
);
1911 Py_END_ALLOW_THREADS
1913 return posix_error();
1916 #endif /* HAVE_FCHOWN */
1919 PyDoc_STRVAR(posix_lchown__doc__
,
1920 "lchown(path, uid, gid)\n\n\
1921 Change the owner and group id of path to the numeric uid and gid.\n\
1922 This function will not follow symbolic links.");
1925 posix_lchown(PyObject
*self
, PyObject
*args
)
1930 if (!PyArg_ParseTuple(args
, "etii:lchown",
1931 Py_FileSystemDefaultEncoding
, &path
,
1934 Py_BEGIN_ALLOW_THREADS
1935 res
= lchown(path
, (uid_t
) uid
, (gid_t
) gid
);
1936 Py_END_ALLOW_THREADS
1938 return posix_error_with_allocated_filename(path
);
1943 #endif /* HAVE_LCHOWN */
1947 PyDoc_STRVAR(posix_getcwd__doc__
,
1948 "getcwd() -> path\n\n\
1949 Return a string representing the current working directory.");
1952 posix_getcwd(PyObject
*self
, PyObject
*noargs
)
1954 int bufsize_incr
= 1024;
1956 char *tmpbuf
= NULL
;
1958 PyObject
*dynamic_return
;
1960 Py_BEGIN_ALLOW_THREADS
1962 bufsize
= bufsize
+ bufsize_incr
;
1963 tmpbuf
= malloc(bufsize
);
1964 if (tmpbuf
== NULL
) {
1967 #if defined(PYOS_OS2) && defined(PYCC_GCC)
1968 res
= _getcwd2(tmpbuf
, bufsize
);
1970 res
= getcwd(tmpbuf
, bufsize
);
1976 } while ((res
== NULL
) && (errno
== ERANGE
));
1977 Py_END_ALLOW_THREADS
1980 return posix_error();
1982 dynamic_return
= PyString_FromString(tmpbuf
);
1985 return dynamic_return
;
1988 #ifdef Py_USING_UNICODE
1989 PyDoc_STRVAR(posix_getcwdu__doc__
,
1990 "getcwdu() -> path\n\n\
1991 Return a unicode string representing the current working directory.");
1994 posix_getcwdu(PyObject
*self
, PyObject
*noargs
)
1999 #ifdef Py_WIN_WIDE_FILENAMES
2001 if (unicode_file_names()) {
2003 wchar_t *wbuf2
= wbuf
;
2005 Py_BEGIN_ALLOW_THREADS
2006 len
= GetCurrentDirectoryW(sizeof wbuf
/ sizeof wbuf
[0], wbuf
);
2007 /* If the buffer is large enough, len does not include the
2008 terminating \0. If the buffer is too small, len includes
2009 the space needed for the terminator. */
2010 if (len
>= sizeof wbuf
/ sizeof wbuf
[0]) {
2011 wbuf2
= malloc(len
* sizeof(wchar_t));
2013 len
= GetCurrentDirectoryW(len
, wbuf2
);
2015 Py_END_ALLOW_THREADS
2021 if (wbuf2
!= wbuf
) free(wbuf2
);
2022 return win32_error("getcwdu", NULL
);
2024 resobj
= PyUnicode_FromWideChar(wbuf2
, len
);
2025 if (wbuf2
!= wbuf
) free(wbuf2
);
2030 Py_BEGIN_ALLOW_THREADS
2031 #if defined(PYOS_OS2) && defined(PYCC_GCC)
2032 res
= _getcwd2(buf
, sizeof buf
);
2034 res
= getcwd(buf
, sizeof buf
);
2036 Py_END_ALLOW_THREADS
2038 return posix_error();
2039 return PyUnicode_Decode(buf
, strlen(buf
), Py_FileSystemDefaultEncoding
,"strict");
2046 PyDoc_STRVAR(posix_link__doc__
,
2047 "link(src, dst)\n\n\
2048 Create a hard link to a file.");
2051 posix_link(PyObject
*self
, PyObject
*args
)
2053 return posix_2str(args
, "etet:link", link
);
2055 #endif /* HAVE_LINK */
2058 PyDoc_STRVAR(posix_listdir__doc__
,
2059 "listdir(path) -> list_of_strings\n\n\
2060 Return a list containing the names of the entries in the directory.\n\
2062 path: path of directory to list\n\
2064 The list is in arbitrary order. It does not include the special\n\
2065 entries '.' and '..' even if they are present in the directory.");
2068 posix_listdir(PyObject
*self
, PyObject
*args
)
2070 /* XXX Should redo this putting the (now four) versions of opendir
2071 in separate files instead of having them all here... */
2072 #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
2077 WIN32_FIND_DATA FileData
;
2078 char namebuf
[MAX_PATH
+5]; /* Overallocate for \\*.*\0 */
2079 char *bufptr
= namebuf
;
2080 Py_ssize_t len
= sizeof(namebuf
)-5; /* only claim to have space for MAX_PATH */
2082 #ifdef Py_WIN_WIDE_FILENAMES
2083 /* If on wide-character-capable OS see if argument
2084 is Unicode and if so use wide API. */
2085 if (unicode_file_names()) {
2087 if (PyArg_ParseTuple(args
, "U:listdir", &po
)) {
2088 WIN32_FIND_DATAW wFileData
;
2089 Py_UNICODE
*wnamebuf
;
2091 /* Overallocate for \\*.*\0 */
2092 len
= PyUnicode_GET_SIZE(po
);
2093 wnamebuf
= malloc((len
+ 5) * sizeof(wchar_t));
2098 wcscpy(wnamebuf
, PyUnicode_AS_UNICODE(po
));
2099 wch
= len
> 0 ? wnamebuf
[len
-1] : '\0';
2100 if (wch
!= L
'/' && wch
!= L
'\\' && wch
!= L
':')
2101 wnamebuf
[len
++] = L
'\\';
2102 wcscpy(wnamebuf
+ len
, L
"*.*");
2103 if ((d
= PyList_New(0)) == NULL
) {
2107 hFindFile
= FindFirstFileW(wnamebuf
, &wFileData
);
2108 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2109 int error
= GetLastError();
2110 if (error
== ERROR_FILE_NOT_FOUND
) {
2115 win32_error_unicode("FindFirstFileW", wnamebuf
);
2120 /* Skip over . and .. */
2121 if (wcscmp(wFileData
.cFileName
, L
".") != 0 &&
2122 wcscmp(wFileData
.cFileName
, L
"..") != 0) {
2123 v
= PyUnicode_FromUnicode(wFileData
.cFileName
, wcslen(wFileData
.cFileName
));
2129 if (PyList_Append(d
, v
) != 0) {
2137 Py_BEGIN_ALLOW_THREADS
2138 result
= FindNextFileW(hFindFile
, &wFileData
);
2139 Py_END_ALLOW_THREADS
2140 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2141 it got to the end of the directory. */
2142 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2144 win32_error_unicode("FindNextFileW", wnamebuf
);
2145 FindClose(hFindFile
);
2149 } while (result
== TRUE
);
2151 if (FindClose(hFindFile
) == FALSE
) {
2153 win32_error_unicode("FindClose", wnamebuf
);
2160 /* Drop the argument parsing error as narrow strings
2166 if (!PyArg_ParseTuple(args
, "et#:listdir",
2167 Py_FileSystemDefaultEncoding
, &bufptr
, &len
))
2170 char ch
= namebuf
[len
-1];
2171 if (ch
!= SEP
&& ch
!= ALTSEP
&& ch
!= ':')
2172 namebuf
[len
++] = '/';
2174 strcpy(namebuf
+ len
, "*.*");
2176 if ((d
= PyList_New(0)) == NULL
)
2179 hFindFile
= FindFirstFile(namebuf
, &FileData
);
2180 if (hFindFile
== INVALID_HANDLE_VALUE
) {
2181 int error
= GetLastError();
2182 if (error
== ERROR_FILE_NOT_FOUND
)
2185 return win32_error("FindFirstFile", namebuf
);
2188 /* Skip over . and .. */
2189 if (strcmp(FileData
.cFileName
, ".") != 0 &&
2190 strcmp(FileData
.cFileName
, "..") != 0) {
2191 v
= PyString_FromString(FileData
.cFileName
);
2197 if (PyList_Append(d
, v
) != 0) {
2205 Py_BEGIN_ALLOW_THREADS
2206 result
= FindNextFile(hFindFile
, &FileData
);
2207 Py_END_ALLOW_THREADS
2208 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
2209 it got to the end of the directory. */
2210 if (!result
&& GetLastError() != ERROR_NO_MORE_FILES
) {
2212 win32_error("FindNextFile", namebuf
);
2213 FindClose(hFindFile
);
2216 } while (result
== TRUE
);
2218 if (FindClose(hFindFile
) == FALSE
) {
2220 return win32_error("FindClose", namebuf
);
2225 #elif defined(PYOS_OS2)
2228 #define MAX_PATH CCHMAXPATH
2233 char namebuf
[MAX_PATH
+5];
2239 if (!PyArg_ParseTuple(args
, "t#:listdir", &name
, &len
))
2241 if (len
>= MAX_PATH
) {
2242 PyErr_SetString(PyExc_ValueError
, "path too long");
2245 strcpy(namebuf
, name
);
2246 for (pt
= namebuf
; *pt
; pt
++)
2249 if (namebuf
[len
-1] != SEP
)
2250 namebuf
[len
++] = SEP
;
2251 strcpy(namebuf
+ len
, "*.*");
2253 if ((d
= PyList_New(0)) == NULL
)
2256 rc
= DosFindFirst(namebuf
, /* Wildcard Pattern to Match */
2257 &hdir
, /* Handle to Use While Search Directory */
2258 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
2259 &ep
, sizeof(ep
), /* Structure to Receive Directory Entry */
2260 &srchcnt
, /* Max and Actual Count of Entries Per Iteration */
2261 FIL_STANDARD
); /* Format of Entry (EAs or Not) */
2263 if (rc
!= NO_ERROR
) {
2265 return posix_error_with_filename(name
);
2268 if (srchcnt
> 0) { /* If Directory is NOT Totally Empty, */
2270 if (ep
.achName
[0] == '.'
2271 && (ep
.achName
[1] == '\0' || (ep
.achName
[1] == '.' && ep
.achName
[2] == '\0')))
2272 continue; /* Skip Over "." and ".." Names */
2274 strcpy(namebuf
, ep
.achName
);
2276 /* Leave Case of Name Alone -- In Native Form */
2277 /* (Removed Forced Lowercasing Code) */
2279 v
= PyString_FromString(namebuf
);
2285 if (PyList_Append(d
, v
) != 0) {
2292 } while (DosFindNext(hdir
, &ep
, sizeof(ep
), &srchcnt
) == NO_ERROR
&& srchcnt
> 0);
2302 int arg_is_unicode
= 1;
2305 if (!PyArg_ParseTuple(args
, "U:listdir", &v
)) {
2309 if (!PyArg_ParseTuple(args
, "et:listdir", Py_FileSystemDefaultEncoding
, &name
))
2311 if ((dirp
= opendir(name
)) == NULL
) {
2312 return posix_error_with_allocated_filename(name
);
2314 if ((d
= PyList_New(0)) == NULL
) {
2321 Py_BEGIN_ALLOW_THREADS
2323 Py_END_ALLOW_THREADS
2330 return posix_error_with_allocated_filename(name
);
2333 if (ep
->d_name
[0] == '.' &&
2335 (ep
->d_name
[1] == '.' && NAMLEN(ep
) == 2)))
2337 v
= PyString_FromStringAndSize(ep
->d_name
, NAMLEN(ep
));
2343 #ifdef Py_USING_UNICODE
2344 if (arg_is_unicode
) {
2347 w
= PyUnicode_FromEncodedObject(v
,
2348 Py_FileSystemDefaultEncoding
,
2355 /* fall back to the original byte string, as
2356 discussed in patch #683592 */
2361 if (PyList_Append(d
, v
) != 0) {
2374 #endif /* which OS */
2375 } /* end of posix_listdir */
2378 /* A helper function for abspath on win32 */
2380 posix__getfullpathname(PyObject
*self
, PyObject
*args
)
2382 /* assume encoded strings wont more than double no of chars */
2383 char inbuf
[MAX_PATH
*2];
2384 char *inbufp
= inbuf
;
2385 Py_ssize_t insize
= sizeof(inbuf
);
2386 char outbuf
[MAX_PATH
*2];
2388 #ifdef Py_WIN_WIDE_FILENAMES
2389 if (unicode_file_names()) {
2390 PyUnicodeObject
*po
;
2391 if (PyArg_ParseTuple(args
, "U|:_getfullpathname", &po
)) {
2392 Py_UNICODE
*wpath
= PyUnicode_AS_UNICODE(po
);
2393 Py_UNICODE woutbuf
[MAX_PATH
*2], *woutbufp
= woutbuf
;
2397 result
= GetFullPathNameW(wpath
,
2398 sizeof(woutbuf
)/sizeof(woutbuf
[0]),
2400 if (result
> sizeof(woutbuf
)/sizeof(woutbuf
[0])) {
2401 woutbufp
= malloc(result
* sizeof(Py_UNICODE
));
2403 return PyErr_NoMemory();
2404 result
= GetFullPathNameW(wpath
, result
, woutbufp
, &wtemp
);
2407 v
= PyUnicode_FromUnicode(woutbufp
, wcslen(woutbufp
));
2409 v
= win32_error_unicode("GetFullPathNameW", wpath
);
2410 if (woutbufp
!= woutbuf
)
2414 /* Drop the argument parsing error as narrow strings
2419 if (!PyArg_ParseTuple (args
, "et#:_getfullpathname",
2420 Py_FileSystemDefaultEncoding
, &inbufp
,
2423 if (!GetFullPathName(inbuf
, sizeof(outbuf
)/sizeof(outbuf
[0]),
2425 return win32_error("GetFullPathName", inbuf
);
2426 if (PyUnicode_Check(PyTuple_GetItem(args
, 0))) {
2427 return PyUnicode_Decode(outbuf
, strlen(outbuf
),
2428 Py_FileSystemDefaultEncoding
, NULL
);
2430 return PyString_FromString(outbuf
);
2431 } /* end of posix__getfullpathname */
2432 #endif /* MS_WINDOWS */
2434 PyDoc_STRVAR(posix_mkdir__doc__
,
2435 "mkdir(path [, mode=0777])\n\n\
2436 Create a directory.");
2439 posix_mkdir(PyObject
*self
, PyObject
*args
)
2445 #ifdef Py_WIN_WIDE_FILENAMES
2446 if (unicode_file_names()) {
2447 PyUnicodeObject
*po
;
2448 if (PyArg_ParseTuple(args
, "U|i:mkdir", &po
, &mode
)) {
2449 Py_BEGIN_ALLOW_THREADS
2450 /* PyUnicode_AS_UNICODE OK without thread lock as
2451 it is a simple dereference. */
2452 res
= CreateDirectoryW(PyUnicode_AS_UNICODE(po
), NULL
);
2453 Py_END_ALLOW_THREADS
2455 return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po
));
2459 /* Drop the argument parsing error as narrow strings
2463 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2464 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2466 Py_BEGIN_ALLOW_THREADS
2467 /* PyUnicode_AS_UNICODE OK without thread lock as
2468 it is a simple dereference. */
2469 res
= CreateDirectoryA(path
, NULL
);
2470 Py_END_ALLOW_THREADS
2472 win32_error("mkdir", path
);
2481 if (!PyArg_ParseTuple(args
, "et|i:mkdir",
2482 Py_FileSystemDefaultEncoding
, &path
, &mode
))
2484 Py_BEGIN_ALLOW_THREADS
2485 #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
2488 res
= mkdir(path
, mode
);
2490 Py_END_ALLOW_THREADS
2492 return posix_error_with_allocated_filename(path
);
2500 /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
2501 #if defined(HAVE_SYS_RESOURCE_H)
2502 #include <sys/resource.h>
2507 PyDoc_STRVAR(posix_nice__doc__
,
2508 "nice(inc) -> new_priority\n\n\
2509 Decrease the priority of process by inc and return the new priority.");
2512 posix_nice(PyObject
*self
, PyObject
*args
)
2514 int increment
, value
;
2516 if (!PyArg_ParseTuple(args
, "i:nice", &increment
))
2519 /* There are two flavours of 'nice': one that returns the new
2520 priority (as required by almost all standards out there) and the
2521 Linux/FreeBSD/BSDI one, which returns '0' on success and advices
2522 the use of getpriority() to get the new priority.
2524 If we are of the nice family that returns the new priority, we
2525 need to clear errno before the call, and check if errno is filled
2526 before calling posix_error() on a returnvalue of -1, because the
2527 -1 may be the actual new priority! */
2530 value
= nice(increment
);
2531 #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
2533 value
= getpriority(PRIO_PROCESS
, 0);
2535 if (value
== -1 && errno
!= 0)
2536 /* either nice() or getpriority() returned an error */
2537 return posix_error();
2538 return PyInt_FromLong((long) value
);
2540 #endif /* HAVE_NICE */
2542 PyDoc_STRVAR(posix_rename__doc__
,
2543 "rename(old, new)\n\n\
2544 Rename a file or directory.");
2547 posix_rename(PyObject
*self
, PyObject
*args
)
2553 if (unicode_file_names()) {
2554 if (!PyArg_ParseTuple(args
, "OO:rename", &o1
, &o2
))
2556 if (!convert_to_unicode(&o1
))
2558 if (!convert_to_unicode(&o2
)) {
2562 Py_BEGIN_ALLOW_THREADS
2563 result
= MoveFileW(PyUnicode_AsUnicode(o1
),
2564 PyUnicode_AsUnicode(o2
));
2565 Py_END_ALLOW_THREADS
2569 return win32_error("rename", NULL
);
2575 if (!PyArg_ParseTuple(args
, "ss:rename", &p1
, &p2
))
2577 Py_BEGIN_ALLOW_THREADS
2578 result
= MoveFileA(p1
, p2
);
2579 Py_END_ALLOW_THREADS
2581 return win32_error("rename", NULL
);
2585 return posix_2str(args
, "etet:rename", rename
);
2590 PyDoc_STRVAR(posix_rmdir__doc__
,
2592 Remove a directory.");
2595 posix_rmdir(PyObject
*self
, PyObject
*args
)
2598 return win32_1str(args
, "rmdir", "s:rmdir", RemoveDirectoryA
, "U:rmdir", RemoveDirectoryW
);
2600 return posix_1str(args
, "et:rmdir", rmdir
);
2605 PyDoc_STRVAR(posix_stat__doc__
,
2606 "stat(path) -> stat result\n\n\
2607 Perform a stat system call on the given path.");
2610 posix_stat(PyObject
*self
, PyObject
*args
)
2613 return posix_do_stat(self
, args
, "et:stat", STAT
, "U:stat", win32_wstat
);
2615 return posix_do_stat(self
, args
, "et:stat", STAT
, NULL
, NULL
);
2621 PyDoc_STRVAR(posix_system__doc__
,
2622 "system(command) -> exit_status\n\n\
2623 Execute the command (a string) in a subshell.");
2626 posix_system(PyObject
*self
, PyObject
*args
)
2630 if (!PyArg_ParseTuple(args
, "s:system", &command
))
2632 Py_BEGIN_ALLOW_THREADS
2633 sts
= system(command
);
2634 Py_END_ALLOW_THREADS
2635 return PyInt_FromLong(sts
);
2640 PyDoc_STRVAR(posix_umask__doc__
,
2641 "umask(new_mask) -> old_mask\n\n\
2642 Set the current numeric umask and return the previous umask.");
2645 posix_umask(PyObject
*self
, PyObject
*args
)
2648 if (!PyArg_ParseTuple(args
, "i:umask", &i
))
2652 return posix_error();
2653 return PyInt_FromLong((long)i
);
2657 PyDoc_STRVAR(posix_unlink__doc__
,
2659 Remove a file (same as remove(path)).");
2661 PyDoc_STRVAR(posix_remove__doc__
,
2663 Remove a file (same as unlink(path)).");
2666 posix_unlink(PyObject
*self
, PyObject
*args
)
2669 return win32_1str(args
, "remove", "s:remove", DeleteFileA
, "U:remove", DeleteFileW
);
2671 return posix_1str(args
, "et:remove", unlink
);
2677 PyDoc_STRVAR(posix_uname__doc__
,
2678 "uname() -> (sysname, nodename, release, version, machine)\n\n\
2679 Return a tuple identifying the current operating system.");
2682 posix_uname(PyObject
*self
, PyObject
*noargs
)
2687 Py_BEGIN_ALLOW_THREADS
2689 Py_END_ALLOW_THREADS
2691 return posix_error();
2692 return Py_BuildValue("(sssss)",
2699 #endif /* HAVE_UNAME */
2702 extract_time(PyObject
*t
, long* sec
, long* usec
)
2705 if (PyFloat_Check(t
)) {
2706 double tval
= PyFloat_AsDouble(t
);
2707 PyObject
*intobj
= Py_TYPE(t
)->tp_as_number
->nb_int(t
);
2710 intval
= PyInt_AsLong(intobj
);
2712 if (intval
== -1 && PyErr_Occurred())
2715 *usec
= (long)((tval
- intval
) * 1e6
); /* can't exceed 1000000 */
2717 /* If rounding gave us a negative number,
2722 intval
= PyInt_AsLong(t
);
2723 if (intval
== -1 && PyErr_Occurred())
2730 PyDoc_STRVAR(posix_utime__doc__
,
2731 "utime(path, (atime, mtime))\n\
2732 utime(path, None)\n\n\
2733 Set the access and modified time of the file to the given values. If the\n\
2734 second form is used, set the access and modified times to the current time.");
2737 posix_utime(PyObject
*self
, PyObject
*args
)
2739 #ifdef Py_WIN_WIDE_FILENAMES
2741 PyUnicodeObject
*obwpath
;
2742 wchar_t *wpath
= NULL
;
2745 long atimesec
, mtimesec
, ausec
, musec
;
2746 FILETIME atime
, mtime
;
2747 PyObject
*result
= NULL
;
2749 if (unicode_file_names()) {
2750 if (PyArg_ParseTuple(args
, "UO|:utime", &obwpath
, &arg
)) {
2751 wpath
= PyUnicode_AS_UNICODE(obwpath
);
2752 Py_BEGIN_ALLOW_THREADS
2753 hFile
= CreateFileW(wpath
, FILE_WRITE_ATTRIBUTES
, 0,
2754 NULL
, OPEN_EXISTING
,
2755 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2756 Py_END_ALLOW_THREADS
2757 if (hFile
== INVALID_HANDLE_VALUE
)
2758 return win32_error_unicode("utime", wpath
);
2760 /* Drop the argument parsing error as narrow strings
2765 if (!PyArg_ParseTuple(args
, "etO:utime",
2766 Py_FileSystemDefaultEncoding
, &apath
, &arg
))
2768 Py_BEGIN_ALLOW_THREADS
2769 hFile
= CreateFileA(apath
, FILE_WRITE_ATTRIBUTES
, 0,
2770 NULL
, OPEN_EXISTING
,
2771 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2772 Py_END_ALLOW_THREADS
2773 if (hFile
== INVALID_HANDLE_VALUE
) {
2774 win32_error("utime", apath
);
2781 if (arg
== Py_None
) {
2783 GetSystemTime(&now
);
2784 if (!SystemTimeToFileTime(&now
, &mtime
) ||
2785 !SystemTimeToFileTime(&now
, &atime
)) {
2786 win32_error("utime", NULL
);
2790 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2791 PyErr_SetString(PyExc_TypeError
,
2792 "utime() arg 2 must be a tuple (atime, mtime)");
2796 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2797 &atimesec
, &ausec
) == -1)
2799 time_t_to_FILE_TIME(atimesec
, 1000*ausec
, &atime
);
2800 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2801 &mtimesec
, &musec
) == -1)
2803 time_t_to_FILE_TIME(mtimesec
, 1000*musec
, &mtime
);
2805 if (!SetFileTime(hFile
, NULL
, &atime
, &mtime
)) {
2806 /* Avoid putting the file name into the error here,
2807 as that may confuse the user into believing that
2808 something is wrong with the file, when it also
2809 could be the time stamp that gives a problem. */
2810 win32_error("utime", NULL
);
2817 #else /* Py_WIN_WIDE_FILENAMES */
2820 long atime
, mtime
, ausec
, musec
;
2824 #if defined(HAVE_UTIMES)
2825 struct timeval buf
[2];
2826 #define ATIME buf[0].tv_sec
2827 #define MTIME buf[1].tv_sec
2828 #elif defined(HAVE_UTIME_H)
2829 /* XXX should define struct utimbuf instead, above */
2831 #define ATIME buf.actime
2832 #define MTIME buf.modtime
2833 #define UTIME_ARG &buf
2834 #else /* HAVE_UTIMES */
2836 #define ATIME buf[0]
2837 #define MTIME buf[1]
2838 #define UTIME_ARG buf
2839 #endif /* HAVE_UTIMES */
2842 if (!PyArg_ParseTuple(args
, "etO:utime",
2843 Py_FileSystemDefaultEncoding
, &path
, &arg
))
2845 if (arg
== Py_None
) {
2846 /* optional time values not given */
2847 Py_BEGIN_ALLOW_THREADS
2848 res
= utime(path
, NULL
);
2849 Py_END_ALLOW_THREADS
2851 else if (!PyTuple_Check(arg
) || PyTuple_Size(arg
) != 2) {
2852 PyErr_SetString(PyExc_TypeError
,
2853 "utime() arg 2 must be a tuple (atime, mtime)");
2858 if (extract_time(PyTuple_GET_ITEM(arg
, 0),
2859 &atime
, &ausec
) == -1) {
2863 if (extract_time(PyTuple_GET_ITEM(arg
, 1),
2864 &mtime
, &musec
) == -1) {
2871 buf
[0].tv_usec
= ausec
;
2872 buf
[1].tv_usec
= musec
;
2873 Py_BEGIN_ALLOW_THREADS
2874 res
= utimes(path
, buf
);
2875 Py_END_ALLOW_THREADS
2877 Py_BEGIN_ALLOW_THREADS
2878 res
= utime(path
, UTIME_ARG
);
2879 Py_END_ALLOW_THREADS
2880 #endif /* HAVE_UTIMES */
2883 return posix_error_with_allocated_filename(path
);
2891 #endif /* Py_WIN_WIDE_FILENAMES */
2895 /* Process operations */
2897 PyDoc_STRVAR(posix__exit__doc__
,
2899 Exit to the system with specified status, without normal exit processing.");
2902 posix__exit(PyObject
*self
, PyObject
*args
)
2905 if (!PyArg_ParseTuple(args
, "i:_exit", &sts
))
2908 return NULL
; /* Make gcc -Wall happy */
2911 #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
2913 free_string_array(char **array
, Py_ssize_t count
)
2916 for (i
= 0; i
< count
; i
++)
2917 PyMem_Free(array
[i
]);
2924 PyDoc_STRVAR(posix_execv__doc__
,
2925 "execv(path, args)\n\n\
2926 Execute an executable path with arguments, replacing current process.\n\
2928 path: path of executable file\n\
2929 args: tuple or list of strings");
2932 posix_execv(PyObject
*self
, PyObject
*args
)
2938 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
2940 /* execv has two arguments: (path, argv), where
2941 argv is a list or tuple of strings. */
2943 if (!PyArg_ParseTuple(args
, "etO:execv",
2944 Py_FileSystemDefaultEncoding
,
2947 if (PyList_Check(argv
)) {
2948 argc
= PyList_Size(argv
);
2949 getitem
= PyList_GetItem
;
2951 else if (PyTuple_Check(argv
)) {
2952 argc
= PyTuple_Size(argv
);
2953 getitem
= PyTuple_GetItem
;
2956 PyErr_SetString(PyExc_TypeError
, "execv() arg 2 must be a tuple or list");
2961 argvlist
= PyMem_NEW(char *, argc
+1);
2962 if (argvlist
== NULL
) {
2964 return PyErr_NoMemory();
2966 for (i
= 0; i
< argc
; i
++) {
2967 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
2968 Py_FileSystemDefaultEncoding
,
2970 free_string_array(argvlist
, i
);
2971 PyErr_SetString(PyExc_TypeError
,
2972 "execv() arg 2 must contain only strings");
2978 argvlist
[argc
] = NULL
;
2980 execv(path
, argvlist
);
2982 /* If we get here it's definitely an error */
2984 free_string_array(argvlist
, argc
);
2986 return posix_error();
2990 PyDoc_STRVAR(posix_execve__doc__
,
2991 "execve(path, args, env)\n\n\
2992 Execute a path with arguments and environment, replacing current process.\n\
2994 path: path of executable file\n\
2995 args: tuple or list of arguments\n\
2996 env: dictionary of strings mapping to strings");
2999 posix_execve(PyObject
*self
, PyObject
*args
)
3002 PyObject
*argv
, *env
;
3005 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
;
3006 Py_ssize_t i
, pos
, argc
, envc
;
3007 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3008 Py_ssize_t lastarg
= 0;
3010 /* execve has three arguments: (path, argv, env), where
3011 argv is a list or tuple of strings and env is a dictionary
3012 like posix.environ. */
3014 if (!PyArg_ParseTuple(args
, "etOO:execve",
3015 Py_FileSystemDefaultEncoding
,
3016 &path
, &argv
, &env
))
3018 if (PyList_Check(argv
)) {
3019 argc
= PyList_Size(argv
);
3020 getitem
= PyList_GetItem
;
3022 else if (PyTuple_Check(argv
)) {
3023 argc
= PyTuple_Size(argv
);
3024 getitem
= PyTuple_GetItem
;
3027 PyErr_SetString(PyExc_TypeError
,
3028 "execve() arg 2 must be a tuple or list");
3031 if (!PyMapping_Check(env
)) {
3032 PyErr_SetString(PyExc_TypeError
,
3033 "execve() arg 3 must be a mapping object");
3037 argvlist
= PyMem_NEW(char *, argc
+1);
3038 if (argvlist
== NULL
) {
3042 for (i
= 0; i
< argc
; i
++) {
3043 if (!PyArg_Parse((*getitem
)(argv
, i
),
3044 "et;execve() arg 2 must contain only strings",
3045 Py_FileSystemDefaultEncoding
,
3053 argvlist
[argc
] = NULL
;
3055 i
= PyMapping_Size(env
);
3058 envlist
= PyMem_NEW(char *, i
+ 1);
3059 if (envlist
== NULL
) {
3064 keys
= PyMapping_Keys(env
);
3065 vals
= PyMapping_Values(env
);
3068 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3069 PyErr_SetString(PyExc_TypeError
,
3070 "execve(): env.keys() or env.values() is not a list");
3074 for (pos
= 0; pos
< i
; pos
++) {
3078 key
= PyList_GetItem(keys
, pos
);
3079 val
= PyList_GetItem(vals
, pos
);
3085 "s;execve() arg 3 contains a non-string key",
3089 "s;execve() arg 3 contains a non-string value",
3095 #if defined(PYOS_OS2)
3096 /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
3097 if (stricmp(k
, "BEGINLIBPATH") != 0 && stricmp(k
, "ENDLIBPATH") != 0) {
3099 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3100 p
= PyMem_NEW(char, len
);
3105 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3106 envlist
[envc
++] = p
;
3107 #if defined(PYOS_OS2)
3113 execve(path
, argvlist
, envlist
);
3115 /* If we get here it's definitely an error */
3117 (void) posix_error();
3121 PyMem_DEL(envlist
[envc
]);
3124 free_string_array(argvlist
, lastarg
);
3131 #endif /* HAVE_EXECV */
3135 PyDoc_STRVAR(posix_spawnv__doc__
,
3136 "spawnv(mode, path, args)\n\n\
3137 Execute the program 'path' in a new process.\n\
3139 mode: mode of process creation\n\
3140 path: path of executable file\n\
3141 args: tuple or list of strings");
3144 posix_spawnv(PyObject
*self
, PyObject
*args
)
3151 Py_intptr_t spawnval
;
3152 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3154 /* spawnv has three arguments: (mode, path, argv), where
3155 argv is a list or tuple of strings. */
3157 if (!PyArg_ParseTuple(args
, "ietO:spawnv", &mode
,
3158 Py_FileSystemDefaultEncoding
,
3161 if (PyList_Check(argv
)) {
3162 argc
= PyList_Size(argv
);
3163 getitem
= PyList_GetItem
;
3165 else if (PyTuple_Check(argv
)) {
3166 argc
= PyTuple_Size(argv
);
3167 getitem
= PyTuple_GetItem
;
3170 PyErr_SetString(PyExc_TypeError
,
3171 "spawnv() arg 2 must be a tuple or list");
3176 argvlist
= PyMem_NEW(char *, argc
+1);
3177 if (argvlist
== NULL
) {
3179 return PyErr_NoMemory();
3181 for (i
= 0; i
< argc
; i
++) {
3182 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3183 Py_FileSystemDefaultEncoding
,
3185 free_string_array(argvlist
, i
);
3188 "spawnv() arg 2 must contain only strings");
3193 argvlist
[argc
] = NULL
;
3195 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3196 Py_BEGIN_ALLOW_THREADS
3197 spawnval
= spawnv(mode
, path
, argvlist
);
3198 Py_END_ALLOW_THREADS
3200 if (mode
== _OLD_P_OVERLAY
)
3203 Py_BEGIN_ALLOW_THREADS
3204 spawnval
= _spawnv(mode
, path
, argvlist
);
3205 Py_END_ALLOW_THREADS
3208 free_string_array(argvlist
, argc
);
3212 return posix_error();
3214 #if SIZEOF_LONG == SIZEOF_VOID_P
3215 return Py_BuildValue("l", (long) spawnval
);
3217 return Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3222 PyDoc_STRVAR(posix_spawnve__doc__
,
3223 "spawnve(mode, path, args, env)\n\n\
3224 Execute the program 'path' in a new process.\n\
3226 mode: mode of process creation\n\
3227 path: path of executable file\n\
3228 args: tuple or list of arguments\n\
3229 env: dictionary of strings mapping to strings");
3232 posix_spawnve(PyObject
*self
, PyObject
*args
)
3235 PyObject
*argv
, *env
;
3238 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3239 int mode
, pos
, envc
;
3241 Py_intptr_t spawnval
;
3242 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3243 Py_ssize_t lastarg
= 0;
3245 /* spawnve has four arguments: (mode, path, argv, env), where
3246 argv is a list or tuple of strings and env is a dictionary
3247 like posix.environ. */
3249 if (!PyArg_ParseTuple(args
, "ietOO:spawnve", &mode
,
3250 Py_FileSystemDefaultEncoding
,
3251 &path
, &argv
, &env
))
3253 if (PyList_Check(argv
)) {
3254 argc
= PyList_Size(argv
);
3255 getitem
= PyList_GetItem
;
3257 else if (PyTuple_Check(argv
)) {
3258 argc
= PyTuple_Size(argv
);
3259 getitem
= PyTuple_GetItem
;
3262 PyErr_SetString(PyExc_TypeError
,
3263 "spawnve() arg 2 must be a tuple or list");
3266 if (!PyMapping_Check(env
)) {
3267 PyErr_SetString(PyExc_TypeError
,
3268 "spawnve() arg 3 must be a mapping object");
3272 argvlist
= PyMem_NEW(char *, argc
+1);
3273 if (argvlist
== NULL
) {
3277 for (i
= 0; i
< argc
; i
++) {
3278 if (!PyArg_Parse((*getitem
)(argv
, i
),
3279 "et;spawnve() arg 2 must contain only strings",
3280 Py_FileSystemDefaultEncoding
,
3288 argvlist
[argc
] = NULL
;
3290 i
= PyMapping_Size(env
);
3293 envlist
= PyMem_NEW(char *, i
+ 1);
3294 if (envlist
== NULL
) {
3299 keys
= PyMapping_Keys(env
);
3300 vals
= PyMapping_Values(env
);
3303 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3304 PyErr_SetString(PyExc_TypeError
,
3305 "spawnve(): env.keys() or env.values() is not a list");
3309 for (pos
= 0; pos
< i
; pos
++) {
3313 key
= PyList_GetItem(keys
, pos
);
3314 val
= PyList_GetItem(vals
, pos
);
3320 "s;spawnve() arg 3 contains a non-string key",
3324 "s;spawnve() arg 3 contains a non-string value",
3329 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3330 p
= PyMem_NEW(char, len
);
3335 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3336 envlist
[envc
++] = p
;
3340 #if defined(PYOS_OS2) && defined(PYCC_GCC)
3341 Py_BEGIN_ALLOW_THREADS
3342 spawnval
= spawnve(mode
, path
, argvlist
, envlist
);
3343 Py_END_ALLOW_THREADS
3345 if (mode
== _OLD_P_OVERLAY
)
3348 Py_BEGIN_ALLOW_THREADS
3349 spawnval
= _spawnve(mode
, path
, argvlist
, envlist
);
3350 Py_END_ALLOW_THREADS
3354 (void) posix_error();
3356 #if SIZEOF_LONG == SIZEOF_VOID_P
3357 res
= Py_BuildValue("l", (long) spawnval
);
3359 res
= Py_BuildValue("L", (PY_LONG_LONG
) spawnval
);
3364 PyMem_DEL(envlist
[envc
]);
3367 free_string_array(argvlist
, lastarg
);
3375 /* OS/2 supports spawnvp & spawnvpe natively */
3376 #if defined(PYOS_OS2)
3377 PyDoc_STRVAR(posix_spawnvp__doc__
,
3378 "spawnvp(mode, file, args)\n\n\
3379 Execute the program 'file' in a new process, using the environment\n\
3380 search path to find the file.\n\
3382 mode: mode of process creation\n\
3383 file: executable file name\n\
3384 args: tuple or list of strings");
3387 posix_spawnvp(PyObject
*self
, PyObject
*args
)
3393 Py_intptr_t spawnval
;
3394 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3396 /* spawnvp has three arguments: (mode, path, argv), where
3397 argv is a list or tuple of strings. */
3399 if (!PyArg_ParseTuple(args
, "ietO:spawnvp", &mode
,
3400 Py_FileSystemDefaultEncoding
,
3403 if (PyList_Check(argv
)) {
3404 argc
= PyList_Size(argv
);
3405 getitem
= PyList_GetItem
;
3407 else if (PyTuple_Check(argv
)) {
3408 argc
= PyTuple_Size(argv
);
3409 getitem
= PyTuple_GetItem
;
3412 PyErr_SetString(PyExc_TypeError
,
3413 "spawnvp() arg 2 must be a tuple or list");
3418 argvlist
= PyMem_NEW(char *, argc
+1);
3419 if (argvlist
== NULL
) {
3421 return PyErr_NoMemory();
3423 for (i
= 0; i
< argc
; i
++) {
3424 if (!PyArg_Parse((*getitem
)(argv
, i
), "et",
3425 Py_FileSystemDefaultEncoding
,
3427 free_string_array(argvlist
, i
);
3430 "spawnvp() arg 2 must contain only strings");
3435 argvlist
[argc
] = NULL
;
3437 Py_BEGIN_ALLOW_THREADS
3438 #if defined(PYCC_GCC)
3439 spawnval
= spawnvp(mode
, path
, argvlist
);
3441 spawnval
= _spawnvp(mode
, path
, argvlist
);
3443 Py_END_ALLOW_THREADS
3445 free_string_array(argvlist
, argc
);
3449 return posix_error();
3451 return Py_BuildValue("l", (long) spawnval
);
3455 PyDoc_STRVAR(posix_spawnvpe__doc__
,
3456 "spawnvpe(mode, file, args, env)\n\n\
3457 Execute the program 'file' in a new process, using the environment\n\
3458 search path to find the file.\n\
3460 mode: mode of process creation\n\
3461 file: executable file name\n\
3462 args: tuple or list of arguments\n\
3463 env: dictionary of strings mapping to strings");
3466 posix_spawnvpe(PyObject
*self
, PyObject
*args
)
3469 PyObject
*argv
, *env
;
3472 PyObject
*key
, *val
, *keys
=NULL
, *vals
=NULL
, *res
=NULL
;
3473 int mode
, i
, pos
, argc
, envc
;
3474 Py_intptr_t spawnval
;
3475 PyObject
*(*getitem
)(PyObject
*, Py_ssize_t
);
3478 /* spawnvpe has four arguments: (mode, path, argv, env), where
3479 argv is a list or tuple of strings and env is a dictionary
3480 like posix.environ. */
3482 if (!PyArg_ParseTuple(args
, "ietOO:spawnvpe", &mode
,
3483 Py_FileSystemDefaultEncoding
,
3484 &path
, &argv
, &env
))
3486 if (PyList_Check(argv
)) {
3487 argc
= PyList_Size(argv
);
3488 getitem
= PyList_GetItem
;
3490 else if (PyTuple_Check(argv
)) {
3491 argc
= PyTuple_Size(argv
);
3492 getitem
= PyTuple_GetItem
;
3495 PyErr_SetString(PyExc_TypeError
,
3496 "spawnvpe() arg 2 must be a tuple or list");
3499 if (!PyMapping_Check(env
)) {
3500 PyErr_SetString(PyExc_TypeError
,
3501 "spawnvpe() arg 3 must be a mapping object");
3505 argvlist
= PyMem_NEW(char *, argc
+1);
3506 if (argvlist
== NULL
) {
3510 for (i
= 0; i
< argc
; i
++) {
3511 if (!PyArg_Parse((*getitem
)(argv
, i
),
3512 "et;spawnvpe() arg 2 must contain only strings",
3513 Py_FileSystemDefaultEncoding
,
3521 argvlist
[argc
] = NULL
;
3523 i
= PyMapping_Size(env
);
3526 envlist
= PyMem_NEW(char *, i
+ 1);
3527 if (envlist
== NULL
) {
3532 keys
= PyMapping_Keys(env
);
3533 vals
= PyMapping_Values(env
);
3536 if (!PyList_Check(keys
) || !PyList_Check(vals
)) {
3537 PyErr_SetString(PyExc_TypeError
,
3538 "spawnvpe(): env.keys() or env.values() is not a list");
3542 for (pos
= 0; pos
< i
; pos
++) {
3546 key
= PyList_GetItem(keys
, pos
);
3547 val
= PyList_GetItem(vals
, pos
);
3553 "s;spawnvpe() arg 3 contains a non-string key",
3557 "s;spawnvpe() arg 3 contains a non-string value",
3562 len
= PyString_Size(key
) + PyString_Size(val
) + 2;
3563 p
= PyMem_NEW(char, len
);
3568 PyOS_snprintf(p
, len
, "%s=%s", k
, v
);
3569 envlist
[envc
++] = p
;
3573 Py_BEGIN_ALLOW_THREADS
3574 #if defined(PYCC_GCC)
3575 spawnval
= spawnvpe(mode
, path
, argvlist
, envlist
);
3577 spawnval
= _spawnvpe(mode
, path
, argvlist
, envlist
);
3579 Py_END_ALLOW_THREADS
3582 (void) posix_error();
3584 res
= Py_BuildValue("l", (long) spawnval
);
3588 PyMem_DEL(envlist
[envc
]);
3591 free_string_array(argvlist
, lastarg
);
3598 #endif /* PYOS_OS2 */
3599 #endif /* HAVE_SPAWNV */
3603 PyDoc_STRVAR(posix_fork1__doc__
,
3604 "fork1() -> pid\n\n\
3605 Fork a child process with a single multiplexed (i.e., not bound) thread.\n\
3607 Return 0 to child process and PID of child to parent process.");
3610 posix_fork1(PyObject
*self
, PyObject
*noargs
)
3612 pid_t pid
= fork1();
3614 return posix_error();
3617 return PyInt_FromLong(pid
);
3623 PyDoc_STRVAR(posix_fork__doc__
,
3625 Fork a child process.\n\
3626 Return 0 to child process and PID of child to parent process.");
3629 posix_fork(PyObject
*self
, PyObject
*noargs
)
3633 return posix_error();
3636 return PyInt_FromLong(pid
);
3640 /* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
3641 /* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
3642 #if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
3643 #define DEV_PTY_FILE "/dev/ptc"
3644 #define HAVE_DEV_PTMX
3646 #define DEV_PTY_FILE "/dev/ptmx"
3649 #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
3653 #ifdef HAVE_LIBUTIL_H
3654 #include <libutil.h>
3655 #endif /* HAVE_LIBUTIL_H */
3656 #endif /* HAVE_PTY_H */
3657 #ifdef HAVE_STROPTS_H
3658 #include <stropts.h>
3660 #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX */
3662 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
3663 PyDoc_STRVAR(posix_openpty__doc__
,
3664 "openpty() -> (master_fd, slave_fd)\n\n\
3665 Open a pseudo-terminal, returning open fd's for both master and slave end.\n");
3668 posix_openpty(PyObject
*self
, PyObject
*noargs
)
3670 int master_fd
, slave_fd
;
3671 #ifndef HAVE_OPENPTY
3674 #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
3675 PyOS_sighandler_t sig_saved
;
3677 extern char *ptsname(int fildes
);
3682 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) != 0)
3683 return posix_error();
3684 #elif defined(HAVE__GETPTY)
3685 slave_name
= _getpty(&master_fd
, O_RDWR
, 0666, 0);
3686 if (slave_name
== NULL
)
3687 return posix_error();
3689 slave_fd
= open(slave_name
, O_RDWR
);
3691 return posix_error();
3693 master_fd
= open(DEV_PTY_FILE
, O_RDWR
| O_NOCTTY
); /* open master */
3695 return posix_error();
3696 sig_saved
= PyOS_setsig(SIGCHLD
, SIG_DFL
);
3697 /* change permission of slave */
3698 if (grantpt(master_fd
) < 0) {
3699 PyOS_setsig(SIGCHLD
, sig_saved
);
3700 return posix_error();
3703 if (unlockpt(master_fd
) < 0) {
3704 PyOS_setsig(SIGCHLD
, sig_saved
);
3705 return posix_error();
3707 PyOS_setsig(SIGCHLD
, sig_saved
);
3708 slave_name
= ptsname(master_fd
); /* get name of slave */
3709 if (slave_name
== NULL
)
3710 return posix_error();
3711 slave_fd
= open(slave_name
, O_RDWR
| O_NOCTTY
); /* open slave */
3713 return posix_error();
3714 #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC)
3715 ioctl(slave_fd
, I_PUSH
, "ptem"); /* push ptem */
3716 ioctl(slave_fd
, I_PUSH
, "ldterm"); /* push ldterm */
3718 ioctl(slave_fd
, I_PUSH
, "ttcompat"); /* push ttcompat */
3720 #endif /* HAVE_CYGWIN */
3721 #endif /* HAVE_OPENPTY */
3723 return Py_BuildValue("(ii)", master_fd
, slave_fd
);
3726 #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
3729 PyDoc_STRVAR(posix_forkpty__doc__
,
3730 "forkpty() -> (pid, master_fd)\n\n\
3731 Fork a new process with a new pseudo-terminal as controlling tty.\n\n\
3732 Like fork(), return 0 as pid to child process, and PID of child to parent.\n\
3733 To both, return fd of newly opened pseudo-terminal.\n");
3736 posix_forkpty(PyObject
*self
, PyObject
*noargs
)
3741 pid
= forkpty(&master_fd
, NULL
, NULL
, NULL
);
3743 return posix_error();
3746 return Py_BuildValue("(li)", pid
, master_fd
);
3751 PyDoc_STRVAR(posix_getegid__doc__
,
3752 "getegid() -> egid\n\n\
3753 Return the current process's effective group id.");
3756 posix_getegid(PyObject
*self
, PyObject
*noargs
)
3758 return PyInt_FromLong((long)getegid());
3764 PyDoc_STRVAR(posix_geteuid__doc__
,
3765 "geteuid() -> euid\n\n\
3766 Return the current process's effective user id.");
3769 posix_geteuid(PyObject
*self
, PyObject
*noargs
)
3771 return PyInt_FromLong((long)geteuid());
3777 PyDoc_STRVAR(posix_getgid__doc__
,
3778 "getgid() -> gid\n\n\
3779 Return the current process's group id.");
3782 posix_getgid(PyObject
*self
, PyObject
*noargs
)
3784 return PyInt_FromLong((long)getgid());
3789 PyDoc_STRVAR(posix_getpid__doc__
,
3790 "getpid() -> pid\n\n\
3791 Return the current process id");
3794 posix_getpid(PyObject
*self
, PyObject
*noargs
)
3796 return PyInt_FromLong((long)getpid());
3800 #ifdef HAVE_GETGROUPS
3801 PyDoc_STRVAR(posix_getgroups__doc__
,
3802 "getgroups() -> list of group IDs\n\n\
3803 Return list of supplemental group IDs for the process.");
3806 posix_getgroups(PyObject
*self
, PyObject
*noargs
)
3808 PyObject
*result
= NULL
;
3811 #define MAX_GROUPS NGROUPS_MAX
3813 /* defined to be 16 on Solaris7, so this should be a small number */
3814 #define MAX_GROUPS 64
3816 gid_t grouplist
[MAX_GROUPS
];
3819 n
= getgroups(MAX_GROUPS
, grouplist
);
3823 result
= PyList_New(n
);
3824 if (result
!= NULL
) {
3826 for (i
= 0; i
< n
; ++i
) {
3827 PyObject
*o
= PyInt_FromLong((long)grouplist
[i
]);
3833 PyList_SET_ITEM(result
, i
, o
);
3843 PyDoc_STRVAR(posix_getpgid__doc__
,
3844 "getpgid(pid) -> pgid\n\n\
3845 Call the system call getpgid().");
3848 posix_getpgid(PyObject
*self
, PyObject
*args
)
3851 if (!PyArg_ParseTuple(args
, "i:getpgid", &pid
))
3853 pgid
= getpgid(pid
);
3855 return posix_error();
3856 return PyInt_FromLong((long)pgid
);
3858 #endif /* HAVE_GETPGID */
3862 PyDoc_STRVAR(posix_getpgrp__doc__
,
3863 "getpgrp() -> pgrp\n\n\
3864 Return the current process group id.");
3867 posix_getpgrp(PyObject
*self
, PyObject
*noargs
)
3869 #ifdef GETPGRP_HAVE_ARG
3870 return PyInt_FromLong((long)getpgrp(0));
3871 #else /* GETPGRP_HAVE_ARG */
3872 return PyInt_FromLong((long)getpgrp());
3873 #endif /* GETPGRP_HAVE_ARG */
3875 #endif /* HAVE_GETPGRP */
3879 PyDoc_STRVAR(posix_setpgrp__doc__
,
3881 Make this process a session leader.");
3884 posix_setpgrp(PyObject
*self
, PyObject
*noargs
)
3886 #ifdef SETPGRP_HAVE_ARG
3887 if (setpgrp(0, 0) < 0)
3888 #else /* SETPGRP_HAVE_ARG */
3890 #endif /* SETPGRP_HAVE_ARG */
3891 return posix_error();
3896 #endif /* HAVE_SETPGRP */
3899 PyDoc_STRVAR(posix_getppid__doc__
,
3900 "getppid() -> ppid\n\n\
3901 Return the parent's process id.");
3904 posix_getppid(PyObject
*self
, PyObject
*noargs
)
3906 return PyInt_FromLong(getppid());
3911 #ifdef HAVE_GETLOGIN
3912 PyDoc_STRVAR(posix_getlogin__doc__
,
3913 "getlogin() -> string\n\n\
3914 Return the actual login name.");
3917 posix_getlogin(PyObject
*self
, PyObject
*noargs
)
3919 PyObject
*result
= NULL
;
3921 int old_errno
= errno
;
3929 PyErr_SetString(PyExc_OSError
,
3930 "unable to determine login name");
3933 result
= PyString_FromString(name
);
3941 PyDoc_STRVAR(posix_getuid__doc__
,
3942 "getuid() -> uid\n\n\
3943 Return the current process's user id.");
3946 posix_getuid(PyObject
*self
, PyObject
*noargs
)
3948 return PyInt_FromLong((long)getuid());
3954 PyDoc_STRVAR(posix_kill__doc__
,
3955 "kill(pid, sig)\n\n\
3956 Kill a process with a signal.");
3959 posix_kill(PyObject
*self
, PyObject
*args
)
3963 if (!PyArg_ParseTuple(args
, "ii:kill", &pid
, &sig
))
3965 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
3966 if (sig
== XCPT_SIGNAL_INTR
|| sig
== XCPT_SIGNAL_BREAK
) {
3968 if ((rc
= DosSendSignalException(pid
, sig
)) != NO_ERROR
)
3969 return os2_error(rc
);
3971 } else if (sig
== XCPT_SIGNAL_KILLPROC
) {
3973 if ((rc
= DosKillProcess(DKP_PROCESS
, pid
)) != NO_ERROR
)
3974 return os2_error(rc
);
3977 return NULL
; /* Unrecognized Signal Requested */
3979 if (kill(pid
, sig
) == -1)
3980 return posix_error();
3988 PyDoc_STRVAR(posix_killpg__doc__
,
3989 "killpg(pgid, sig)\n\n\
3990 Kill a process group with a signal.");
3993 posix_killpg(PyObject
*self
, PyObject
*args
)
3996 if (!PyArg_ParseTuple(args
, "ii:killpg", &pgid
, &sig
))
3998 if (killpg(pgid
, sig
) == -1)
3999 return posix_error();
4007 #ifdef HAVE_SYS_LOCK_H
4008 #include <sys/lock.h>
4011 PyDoc_STRVAR(posix_plock__doc__
,
4013 Lock program segments into memory.");
4016 posix_plock(PyObject
*self
, PyObject
*args
)
4019 if (!PyArg_ParseTuple(args
, "i:plock", &op
))
4021 if (plock(op
) == -1)
4022 return posix_error();
4030 PyDoc_STRVAR(posix_popen__doc__
,
4031 "popen(command [, mode='r' [, bufsize]]) -> pipe\n\n\
4032 Open a pipe to/from a command returning a file object.");
4034 #if defined(PYOS_OS2)
4035 #if defined(PYCC_VACPP)
4037 async_system(const char *command
)
4039 char errormsg
[256], args
[1024];
4043 char *shell
= getenv("COMSPEC");
4047 /* avoid overflowing the argument buffer */
4048 if (strlen(shell
) + 3 + strlen(command
) >= 1024)
4049 return ERROR_NOT_ENOUGH_MEMORY
4052 strcat(args
, shell
);
4053 strcat(args
, "/c ");
4054 strcat(args
, command
);
4056 /* execute asynchronously, inheriting the environment */
4057 rc
= DosExecPgm(errormsg
,
4068 popen(const char *command
, const char *mode
, int pipesize
, int *err
)
4074 /* mode determines which of stdin or stdout is reconnected to
4075 * the pipe to the child
4077 if (strchr(mode
, 'r') != NULL
) {
4078 tgt_fd
= 1; /* stdout */
4079 } else if (strchr(mode
, 'w')) {
4080 tgt_fd
= 0; /* stdin */
4082 *err
= ERROR_INVALID_ACCESS
;
4086 /* setup the pipe */
4087 if ((rc
= DosCreatePipe(&pipeh
[0], &pipeh
[1], pipesize
)) != NO_ERROR
) {
4092 /* prevent other threads accessing stdio */
4095 /* reconnect stdio and execute child */
4098 if (dup2(pipeh
[tgtfd
], tgtfd
) == 0) {
4099 DosClose(pipeh
[tgtfd
]);
4100 rc
= async_system(command
);
4107 /* allow other threads access to stdio */
4110 /* if execution of child was successful return file stream */
4112 return fdopen(pipeh
[1 - tgtfd
], mode
);
4114 DosClose(pipeh
[1 - tgtfd
]);
4121 posix_popen(PyObject
*self
, PyObject
*args
)
4125 int err
, bufsize
= -1;
4128 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4130 Py_BEGIN_ALLOW_THREADS
4131 fp
= popen(name
, mode
, (bufsize
> 0) ? bufsize
: 4096, &err
);
4132 Py_END_ALLOW_THREADS
4134 return os2_error(err
);
4136 f
= PyFile_FromFile(fp
, name
, mode
, fclose
);
4138 PyFile_SetBufSize(f
, bufsize
);
4142 #elif defined(PYCC_GCC)
4144 /* standard posix version of popen() support */
4146 posix_popen(PyObject
*self
, PyObject
*args
)
4153 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
4155 Py_BEGIN_ALLOW_THREADS
4156 fp
= popen(name
, mode
);
4157 Py_END_ALLOW_THREADS
4159 return posix_error();
4160 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
4162 PyFile_SetBufSize(f
, bufsize
);
4166 /* fork() under OS/2 has lots'o'warts
4167 * EMX supports pipe() and spawn*() so we can synthesize popen[234]()
4168 * most of this code is a ripoff of the win32 code, but using the
4169 * capabilities of EMX's C library routines
4172 /* These tell _PyPopen() whether to return 1, 2, or 3 file objects. */
4178 static PyObject
*_PyPopen(char *, int, int, int);
4179 static int _PyPclose(FILE *file
);
4182 * Internal dictionary mapping popen* file pointers to process handles,
4183 * for use when retrieving the process exit code. See _PyPclose() below
4184 * for more information on this dictionary's use.
4186 static PyObject
*_PyPopenProcs
= NULL
;
4188 /* os2emx version of popen2()
4190 * The result of this function is a pipe (file) connected to the
4191 * process's stdin, and a pipe connected to the process's stdout.
4195 os2emx_popen2(PyObject
*self
, PyObject
*args
)
4203 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4208 else if (*mode
!= 'b') {
4209 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4214 f
= _PyPopen(cmdstring
, tm
, POPEN_2
, bufsize
);
4220 * Variation on os2emx.popen2
4222 * The result of this function is 3 pipes - the process's stdin,
4227 os2emx_popen3(PyObject
*self
, PyObject
*args
)
4235 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4240 else if (*mode
!= 'b') {
4241 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4246 f
= _PyPopen(cmdstring
, tm
, POPEN_3
, bufsize
);
4252 * Variation on os2emx.popen2
4254 * The result of this function is 2 pipes - the processes stdin,
4255 * and stdout+stderr combined as a single pipe.
4259 os2emx_popen4(PyObject
*self
, PyObject
*args
)
4267 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4272 else if (*mode
!= 'b') {
4273 PyErr_SetString(PyExc_ValueError
, "mode must be 't' or 'b'");
4278 f
= _PyPopen(cmdstring
, tm
, POPEN_4
, bufsize
);
4283 /* a couple of structures for convenient handling of multiple
4284 * file handles and pipes
4298 /* The following code is derived from the win32 code */
4301 _PyPopen(char *cmdstring
, int mode
, int n
, int bufsize
)
4303 struct file_ref stdio
[3];
4304 struct pipe_ref p_fd
[3];
4306 int file_count
, i
, pipe_err
;
4308 char *shell
, *sh_name
, *opt
, *rd_mode
, *wr_mode
;
4309 PyObject
*f
, *p_f
[3];
4311 /* file modes for subsequent fdopen's on pipe handles */
4323 /* prepare shell references */
4324 if ((shell
= getenv("EMXSHELL")) == NULL
)
4325 if ((shell
= getenv("COMSPEC")) == NULL
)
4328 return posix_error();
4331 sh_name
= _getname(shell
);
4332 if (stricmp(sh_name
, "cmd.exe") == 0 || stricmp(sh_name
, "4os2.exe") == 0)
4337 /* save current stdio fds + their flags, and set not inheritable */
4339 while (pipe_err
>= 0 && i
< 3)
4341 pipe_err
= stdio
[i
].handle
= dup(i
);
4342 stdio
[i
].flags
= fcntl(i
, F_GETFD
, 0);
4343 fcntl(stdio
[i
].handle
, F_SETFD
, stdio
[i
].flags
| FD_CLOEXEC
);
4348 /* didn't get them all saved - clean up and bail out */
4349 int saved_err
= errno
;
4352 close(stdio
[i
].handle
);
4355 return posix_error();
4358 /* create pipe ends */
4363 while ((pipe_err
== 0) && (i
< file_count
))
4364 pipe_err
= pipe((int *)&p_fd
[i
++]);
4367 /* didn't get them all made - clean up and bail out */
4374 return posix_error();
4377 /* change the actual standard IO streams over temporarily,
4378 * making the retained pipe ends non-inheritable
4383 if (dup2(p_fd
[0].rd
, 0) == 0)
4386 i
= fcntl(p_fd
[0].wr
, F_GETFD
, 0);
4387 fcntl(p_fd
[0].wr
, F_SETFD
, i
| FD_CLOEXEC
);
4388 if ((p_s
[0] = fdopen(p_fd
[0].wr
, wr_mode
)) == NULL
)
4402 if (dup2(p_fd
[1].wr
, 1) == 1)
4405 i
= fcntl(p_fd
[1].rd
, F_GETFD
, 0);
4406 fcntl(p_fd
[1].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4407 if ((p_s
[1] = fdopen(p_fd
[1].rd
, rd_mode
)) == NULL
)
4419 /* - stderr, as required */
4425 if (dup2(p_fd
[2].wr
, 2) == 2)
4428 i
= fcntl(p_fd
[2].rd
, F_GETFD
, 0);
4429 fcntl(p_fd
[2].rd
, F_SETFD
, i
| FD_CLOEXEC
);
4430 if ((p_s
[2] = fdopen(p_fd
[2].rd
, rd_mode
)) == NULL
)
4445 if (dup2(1, 2) != 2)
4453 /* spawn the child process */
4456 pipe_pid
= spawnlp(P_NOWAIT
, shell
, shell
, opt
, cmdstring
, (char *)0);
4463 /* save the PID into the FILE structure
4464 * NOTE: this implementation doesn't actually
4465 * take advantage of this, but do it for
4466 * completeness - AIM Apr01
4468 for (i
= 0; i
< file_count
; i
++)
4469 p_s
[i
]->_pid
= pipe_pid
;
4473 /* reset standard IO to normal */
4474 for (i
= 0; i
< 3; i
++)
4476 dup2(stdio
[i
].handle
, i
);
4477 fcntl(i
, F_SETFD
, stdio
[i
].flags
);
4478 close(stdio
[i
].handle
);
4481 /* if any remnant problems, clean up and bail out */
4484 for (i
= 0; i
< 3; i
++)
4490 return posix_error_with_filename(cmdstring
);
4493 /* build tuple of file objects to return */
4494 if ((p_f
[0] = PyFile_FromFile(p_s
[0], cmdstring
, wr_mode
, _PyPclose
)) != NULL
)
4495 PyFile_SetBufSize(p_f
[0], bufsize
);
4496 if ((p_f
[1] = PyFile_FromFile(p_s
[1], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4497 PyFile_SetBufSize(p_f
[1], bufsize
);
4500 if ((p_f
[2] = PyFile_FromFile(p_s
[2], cmdstring
, rd_mode
, _PyPclose
)) != NULL
)
4501 PyFile_SetBufSize(p_f
[0], bufsize
);
4502 f
= PyTuple_Pack(3, p_f
[0], p_f
[1], p_f
[2]);
4505 f
= PyTuple_Pack(2, p_f
[0], p_f
[1]);
4508 * Insert the files we've created into the process dictionary
4509 * all referencing the list with the process handle and the
4510 * initial number of files (see description below in _PyPclose).
4511 * Since if _PyPclose later tried to wait on a process when all
4512 * handles weren't closed, it could create a deadlock with the
4513 * child, we spend some energy here to try to ensure that we
4514 * either insert all file handles into the dictionary or none
4515 * at all. It's a little clumsy with the various popen modes
4516 * and variable number of files involved.
4520 _PyPopenProcs
= PyDict_New();
4525 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
[3];
4528 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
4529 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
4531 procObj
= PyList_New(2);
4532 pidObj
= PyInt_FromLong((long) pipe_pid
);
4533 intObj
= PyInt_FromLong((long) file_count
);
4535 if (procObj
&& pidObj
&& intObj
)
4537 PyList_SetItem(procObj
, 0, pidObj
);
4538 PyList_SetItem(procObj
, 1, intObj
);
4540 fileObj
[0] = PyLong_FromVoidPtr(p_s
[0]);
4543 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
4547 fileObj
[1] = PyLong_FromVoidPtr(p_s
[1]);
4550 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
4554 if (file_count
>= 3)
4556 fileObj
[2] = PyLong_FromVoidPtr(p_s
[2]);
4559 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
4565 if (ins_rc
[0] < 0 || !fileObj
[0] ||
4566 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
4567 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2]))
4569 /* Something failed - remove any dictionary
4570 * entries that did make it.
4572 if (!ins_rc
[0] && fileObj
[0])
4574 PyDict_DelItem(_PyPopenProcs
,
4577 if (!ins_rc
[1] && fileObj
[1])
4579 PyDict_DelItem(_PyPopenProcs
,
4582 if (!ins_rc
[2] && fileObj
[2])
4584 PyDict_DelItem(_PyPopenProcs
,
4591 * Clean up our localized references for the dictionary keys
4592 * and value since PyDict_SetItem will Py_INCREF any copies
4593 * that got placed in the dictionary.
4595 Py_XDECREF(procObj
);
4596 Py_XDECREF(fileObj
[0]);
4597 Py_XDECREF(fileObj
[1]);
4598 Py_XDECREF(fileObj
[2]);
4601 /* Child is launched. */
4606 * Wrapper for fclose() to use for popen* files, so we can retrieve the
4607 * exit code for the child process and return as a result of the close.
4609 * This function uses the _PyPopenProcs dictionary in order to map the
4610 * input file pointer to information about the process that was
4611 * originally created by the popen* call that created the file pointer.
4612 * The dictionary uses the file pointer as a key (with one entry
4613 * inserted for each file returned by the original popen* call) and a
4614 * single list object as the value for all files from a single call.
4615 * The list object contains the Win32 process handle at [0], and a file
4616 * count at [1], which is initialized to the total number of file
4617 * handles using that list.
4619 * This function closes whichever handle it is passed, and decrements
4620 * the file count in the dictionary for the process handle pointed to
4621 * by this file. On the last close (when the file count reaches zero),
4622 * this function will wait for the child process and then return its
4623 * exit code as the result of the close() operation. This permits the
4624 * files to be closed in any order - it is always the close() of the
4625 * final handle that will return the exit code.
4627 * NOTE: This function is currently called with the GIL released.
4628 * hence we use the GILState API to manage our state.
4631 static int _PyPclose(FILE *file
)
4636 PyObject
*procObj
, *pidObj
, *intObj
, *fileObj
;
4639 PyGILState_STATE state
;
4642 /* Close the file handle first, to ensure it can't block the
4643 * child from exiting if it's the last handle.
4645 result
= fclose(file
);
4648 state
= PyGILState_Ensure();
4652 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
4653 (procObj
= PyDict_GetItem(_PyPopenProcs
,
4654 fileObj
)) != NULL
&&
4655 (pidObj
= PyList_GetItem(procObj
,0)) != NULL
&&
4656 (intObj
= PyList_GetItem(procObj
,1)) != NULL
)
4658 pipe_pid
= (int) PyInt_AsLong(pidObj
);
4659 file_count
= (int) PyInt_AsLong(intObj
);
4663 /* Still other files referencing process */
4665 PyList_SetItem(procObj
,1,
4666 PyInt_FromLong((long) file_count
));
4670 /* Last file for this process */
4671 if (result
!= EOF
&&
4672 waitpid(pipe_pid
, &exit_code
, 0) == pipe_pid
)
4674 /* extract exit status */
4675 if (WIFEXITED(exit_code
))
4677 result
= WEXITSTATUS(exit_code
);
4687 /* Indicate failure - this will cause the file object
4688 * to raise an I/O error and translate the last
4689 * error code from errno. We do have a problem with
4690 * last errors that overlap the normal errno table,
4691 * but that's a consistent problem with the file object.
4697 /* Remove this file pointer from dictionary */
4698 PyDict_DelItem(_PyPopenProcs
, fileObj
);
4700 if (PyDict_Size(_PyPopenProcs
) == 0)
4702 Py_DECREF(_PyPopenProcs
);
4703 _PyPopenProcs
= NULL
;
4706 } /* if object retrieval ok */
4708 Py_XDECREF(fileObj
);
4709 } /* if _PyPopenProcs */
4712 PyGILState_Release(state
);
4717 #endif /* PYCC_??? */
4719 #elif defined(MS_WINDOWS)
4722 * Portable 'popen' replacement for Win32.
4724 * Written by Bill Tutt <billtut@microsoft.com>. Minor tweaks
4725 * and 2.0 integration by Fredrik Lundh <fredrik@pythonware.com>
4726 * Return code handling by David Bolen <db3l@fitlinxx.com>.
4733 /* These tell _PyPopen() wether to return 1, 2, or 3 file objects. */
4739 static PyObject
*_PyPopen(char *, int, int);
4740 static int _PyPclose(FILE *file
);
4743 * Internal dictionary mapping popen* file pointers to process handles,
4744 * for use when retrieving the process exit code. See _PyPclose() below
4745 * for more information on this dictionary's use.
4747 static PyObject
*_PyPopenProcs
= NULL
;
4750 /* popen that works from a GUI.
4752 * The result of this function is a pipe (file) connected to the
4753 * processes stdin or stdout, depending on the requested mode.
4757 posix_popen(PyObject
*self
, PyObject
*args
)
4765 if (!PyArg_ParseTuple(args
, "s|si:popen", &cmdstring
, &mode
, &bufsize
))
4770 else if (*mode
!= 'w') {
4771 PyErr_SetString(PyExc_ValueError
, "popen() arg 2 must be 'r' or 'w'");
4776 if (bufsize
!= -1) {
4777 PyErr_SetString(PyExc_ValueError
, "popen() arg 3 must be -1");
4781 if (*(mode
+1) == 't')
4782 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4783 else if (*(mode
+1) == 'b')
4784 f
= _PyPopen(cmdstring
, tm
| _O_BINARY
, POPEN_1
);
4786 f
= _PyPopen(cmdstring
, tm
| _O_TEXT
, POPEN_1
);
4791 /* Variation on win32pipe.popen
4793 * The result of this function is a pipe (file) connected to the
4794 * process's stdin, and a pipe connected to the process's stdout.
4798 win32_popen2(PyObject
*self
, PyObject
*args
)
4806 if (!PyArg_ParseTuple(args
, "s|si:popen2", &cmdstring
, &mode
, &bufsize
))
4811 else if (*mode
!= 'b') {
4812 PyErr_SetString(PyExc_ValueError
, "popen2() arg 2 must be 't' or 'b'");
4817 if (bufsize
!= -1) {
4818 PyErr_SetString(PyExc_ValueError
, "popen2() arg 3 must be -1");
4822 f
= _PyPopen(cmdstring
, tm
, POPEN_2
);
4828 * Variation on <om win32pipe.popen>
4830 * The result of this function is 3 pipes - the process's stdin,
4835 win32_popen3(PyObject
*self
, PyObject
*args
)
4843 if (!PyArg_ParseTuple(args
, "s|si:popen3", &cmdstring
, &mode
, &bufsize
))
4848 else if (*mode
!= 'b') {
4849 PyErr_SetString(PyExc_ValueError
, "popen3() arg 2 must be 't' or 'b'");
4854 if (bufsize
!= -1) {
4855 PyErr_SetString(PyExc_ValueError
, "popen3() arg 3 must be -1");
4859 f
= _PyPopen(cmdstring
, tm
, POPEN_3
);
4865 * Variation on win32pipe.popen
4867 * The result of this function is 2 pipes - the processes stdin,
4868 * and stdout+stderr combined as a single pipe.
4872 win32_popen4(PyObject
*self
, PyObject
*args
)
4880 if (!PyArg_ParseTuple(args
, "s|si:popen4", &cmdstring
, &mode
, &bufsize
))
4885 else if (*mode
!= 'b') {
4886 PyErr_SetString(PyExc_ValueError
, "popen4() arg 2 must be 't' or 'b'");
4891 if (bufsize
!= -1) {
4892 PyErr_SetString(PyExc_ValueError
, "popen4() arg 3 must be -1");
4896 f
= _PyPopen(cmdstring
, tm
, POPEN_4
);
4902 _PyPopenCreateProcess(char *cmdstring
,
4908 PROCESS_INFORMATION piProcInfo
;
4909 STARTUPINFO siStartInfo
;
4910 DWORD dwProcessFlags
= 0; /* no NEW_CONSOLE by default for Ctrl+C handling */
4911 char *s1
,*s2
, *s3
= " /c ";
4912 const char *szConsoleSpawn
= "w9xpopen.exe";
4916 if (i
= GetEnvironmentVariable("COMSPEC",NULL
,0)) {
4919 s1
= (char *)alloca(i
);
4920 if (!(x
= GetEnvironmentVariable("COMSPEC", s1
, i
)))
4921 /* x < i, so x fits into an integer */
4924 /* Explicitly check if we are using COMMAND.COM. If we are
4925 * then use the w9xpopen hack.
4928 while (comshell
>= s1
&& *comshell
!= '\\')
4932 if (GetVersion() < 0x80000000 &&
4933 _stricmp(comshell
, "command.com") != 0) {
4934 /* NT/2000 and not using command.com. */
4935 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1;
4936 s2
= (char *)alloca(x
);
4938 PyOS_snprintf(s2
, x
, "%s%s%s", s1
, s3
, cmdstring
);
4942 * Oh gag, we're on Win9x or using COMMAND.COM. Use
4943 * the workaround listed in KB: Q150956
4945 char modulepath
[_MAX_PATH
];
4946 struct stat statinfo
;
4947 GetModuleFileName(NULL
, modulepath
, sizeof(modulepath
));
4948 for (x
= i
= 0; modulepath
[i
]; i
++)
4949 if (modulepath
[i
] == SEP
)
4951 modulepath
[x
] = '\0';
4952 /* Create the full-name to w9xpopen, so we can test it exists */
4955 (sizeof(modulepath
)/sizeof(modulepath
[0]))
4956 -strlen(modulepath
));
4957 if (stat(modulepath
, &statinfo
) != 0) {
4958 size_t mplen
= sizeof(modulepath
)/sizeof(modulepath
[0]);
4959 /* Eeek - file-not-found - possibly an embedding
4960 situation - see if we can locate it in sys.prefix
4965 modulepath
[mplen
-1] = '\0';
4966 if (modulepath
[strlen(modulepath
)-1] != '\\')
4967 strcat(modulepath
, "\\");
4970 mplen
-strlen(modulepath
));
4971 /* No where else to look - raise an easily identifiable
4972 error, rather than leaving Windows to report
4973 "file not found" - as the user is probably blissfully
4974 unaware this shim EXE is used, and it will confuse them.
4975 (well, it confused me for a while ;-)
4977 if (stat(modulepath
, &statinfo
) != 0) {
4978 PyErr_Format(PyExc_RuntimeError
,
4979 "Can not locate '%s' which is needed "
4980 "for popen to work with your shell "
4986 x
= i
+ strlen(s3
) + strlen(cmdstring
) + 1 +
4987 strlen(modulepath
) +
4988 strlen(szConsoleSpawn
) + 1;
4990 s2
= (char *)alloca(x
);
4992 /* To maintain correct argument passing semantics,
4993 we pass the command-line as it stands, and allow
4994 quoting to be applied. w9xpopen.exe will then
4995 use its argv vector, and re-quote the necessary
4996 args for the ultimate child process.
5005 /* Not passing CREATE_NEW_CONSOLE has been known to
5006 cause random failures on win9x. Specifically a
5008 "Your program accessed mem currently in use at xxx"
5009 and a hopeful warning about the stability of your
5011 Cost is Ctrl+C wont kill children, but anyone
5012 who cares can have a go!
5014 dwProcessFlags
|= CREATE_NEW_CONSOLE
;
5018 /* Could be an else here to try cmd.exe / command.com in the path
5019 Now we'll just error out.. */
5021 PyErr_SetString(PyExc_RuntimeError
,
5022 "Cannot locate a COMSPEC environment variable to "
5023 "use as the shell");
5027 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
5028 siStartInfo
.cb
= sizeof(STARTUPINFO
);
5029 siStartInfo
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
5030 siStartInfo
.hStdInput
= hStdin
;
5031 siStartInfo
.hStdOutput
= hStdout
;
5032 siStartInfo
.hStdError
= hStderr
;
5033 siStartInfo
.wShowWindow
= SW_HIDE
;
5035 if (CreateProcess(NULL
,
5045 /* Close the handles now so anyone waiting is woken. */
5046 CloseHandle(piProcInfo
.hThread
);
5048 /* Return process handle */
5049 *hProcess
= piProcInfo
.hProcess
;
5052 win32_error("CreateProcess", s2
);
5056 /* The following code is based off of KB: Q190351 */
5059 _PyPopen(char *cmdstring
, int mode
, int n
)
5061 HANDLE hChildStdinRd
, hChildStdinWr
, hChildStdoutRd
, hChildStdoutWr
,
5062 hChildStderrRd
, hChildStderrWr
, hChildStdinWrDup
, hChildStdoutRdDup
,
5063 hChildStderrRdDup
, hProcess
; /* hChildStdoutWrDup; */
5065 SECURITY_ATTRIBUTES saAttr
;
5072 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
5073 saAttr
.bInheritHandle
= TRUE
;
5074 saAttr
.lpSecurityDescriptor
= NULL
;
5076 if (!CreatePipe(&hChildStdinRd
, &hChildStdinWr
, &saAttr
, 0))
5077 return win32_error("CreatePipe", NULL
);
5079 /* Create new output read handle and the input write handle. Set
5080 * the inheritance properties to FALSE. Otherwise, the child inherits
5081 * these handles; resulting in non-closeable handles to the pipes
5083 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdinWr
,
5084 GetCurrentProcess(), &hChildStdinWrDup
, 0,
5086 DUPLICATE_SAME_ACCESS
);
5088 return win32_error("DuplicateHandle", NULL
);
5090 /* Close the inheritable version of ChildStdin
5091 that we're using. */
5092 CloseHandle(hChildStdinWr
);
5094 if (!CreatePipe(&hChildStdoutRd
, &hChildStdoutWr
, &saAttr
, 0))
5095 return win32_error("CreatePipe", NULL
);
5097 fSuccess
= DuplicateHandle(GetCurrentProcess(), hChildStdoutRd
,
5098 GetCurrentProcess(), &hChildStdoutRdDup
, 0,
5099 FALSE
, DUPLICATE_SAME_ACCESS
);
5101 return win32_error("DuplicateHandle", NULL
);
5103 /* Close the inheritable version of ChildStdout
5104 that we're using. */
5105 CloseHandle(hChildStdoutRd
);
5108 if (!CreatePipe(&hChildStderrRd
, &hChildStderrWr
, &saAttr
, 0))
5109 return win32_error("CreatePipe", NULL
);
5110 fSuccess
= DuplicateHandle(GetCurrentProcess(),
5112 GetCurrentProcess(),
5113 &hChildStderrRdDup
, 0,
5114 FALSE
, DUPLICATE_SAME_ACCESS
);
5116 return win32_error("DuplicateHandle", NULL
);
5117 /* Close the inheritable version of ChildStdErr that we're using. */
5118 CloseHandle(hChildStderrRd
);
5123 switch (mode
& (_O_RDONLY
| _O_TEXT
| _O_BINARY
| _O_WRONLY
)) {
5124 case _O_WRONLY
| _O_TEXT
:
5125 /* Case for writing to child Stdin in text mode. */
5126 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5127 f1
= _fdopen(fd1
, "w");
5128 f
= PyFile_FromFile(f1
, cmdstring
, "w", _PyPclose
);
5129 PyFile_SetBufSize(f
, 0);
5130 /* We don't care about these pipes anymore, so close them. */
5131 CloseHandle(hChildStdoutRdDup
);
5132 CloseHandle(hChildStderrRdDup
);
5135 case _O_RDONLY
| _O_TEXT
:
5136 /* Case for reading from child Stdout in text mode. */
5137 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5138 f1
= _fdopen(fd1
, "r");
5139 f
= PyFile_FromFile(f1
, cmdstring
, "r", _PyPclose
);
5140 PyFile_SetBufSize(f
, 0);
5141 /* We don't care about these pipes anymore, so close them. */
5142 CloseHandle(hChildStdinWrDup
);
5143 CloseHandle(hChildStderrRdDup
);
5146 case _O_RDONLY
| _O_BINARY
:
5147 /* Case for readinig from child Stdout in binary mode. */
5148 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5149 f1
= _fdopen(fd1
, "rb");
5150 f
= PyFile_FromFile(f1
, cmdstring
, "rb", _PyPclose
);
5151 PyFile_SetBufSize(f
, 0);
5152 /* We don't care about these pipes anymore, so close them. */
5153 CloseHandle(hChildStdinWrDup
);
5154 CloseHandle(hChildStderrRdDup
);
5157 case _O_WRONLY
| _O_BINARY
:
5158 /* Case for writing to child Stdin in binary mode. */
5159 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5160 f1
= _fdopen(fd1
, "wb");
5161 f
= PyFile_FromFile(f1
, cmdstring
, "wb", _PyPclose
);
5162 PyFile_SetBufSize(f
, 0);
5163 /* We don't care about these pipes anymore, so close them. */
5164 CloseHandle(hChildStdoutRdDup
);
5165 CloseHandle(hChildStderrRdDup
);
5177 if (mode
& _O_TEXT
) {
5185 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5186 f1
= _fdopen(fd1
, m2
);
5187 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5188 f2
= _fdopen(fd2
, m1
);
5189 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5190 PyFile_SetBufSize(p1
, 0);
5191 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5192 PyFile_SetBufSize(p2
, 0);
5195 CloseHandle(hChildStderrRdDup
);
5197 f
= PyTuple_Pack(2,p1
,p2
);
5207 PyObject
*p1
, *p2
, *p3
;
5209 if (mode
& _O_TEXT
) {
5217 fd1
= _open_osfhandle((Py_intptr_t
)hChildStdinWrDup
, mode
);
5218 f1
= _fdopen(fd1
, m2
);
5219 fd2
= _open_osfhandle((Py_intptr_t
)hChildStdoutRdDup
, mode
);
5220 f2
= _fdopen(fd2
, m1
);
5221 fd3
= _open_osfhandle((Py_intptr_t
)hChildStderrRdDup
, mode
);
5222 f3
= _fdopen(fd3
, m1
);
5223 p1
= PyFile_FromFile(f1
, cmdstring
, m2
, _PyPclose
);
5224 p2
= PyFile_FromFile(f2
, cmdstring
, m1
, _PyPclose
);
5225 p3
= PyFile_FromFile(f3
, cmdstring
, m1
, _PyPclose
);
5226 PyFile_SetBufSize(p1
, 0);
5227 PyFile_SetBufSize(p2
, 0);
5228 PyFile_SetBufSize(p3
, 0);
5229 f
= PyTuple_Pack(3,p1
,p2
,p3
);
5239 if (!_PyPopenCreateProcess(cmdstring
,
5247 if (!_PyPopenCreateProcess(cmdstring
,
5256 * Insert the files we've created into the process dictionary
5257 * all referencing the list with the process handle and the
5258 * initial number of files (see description below in _PyPclose).
5259 * Since if _PyPclose later tried to wait on a process when all
5260 * handles weren't closed, it could create a deadlock with the
5261 * child, we spend some energy here to try to ensure that we
5262 * either insert all file handles into the dictionary or none
5263 * at all. It's a little clumsy with the various popen modes
5264 * and variable number of files involved.
5266 if (!_PyPopenProcs
) {
5267 _PyPopenProcs
= PyDict_New();
5270 if (_PyPopenProcs
) {
5271 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
[3];
5274 fileObj
[0] = fileObj
[1] = fileObj
[2] = NULL
;
5275 ins_rc
[0] = ins_rc
[1] = ins_rc
[2] = 0;
5277 procObj
= PyList_New(2);
5278 hProcessObj
= PyLong_FromVoidPtr(hProcess
);
5279 intObj
= PyInt_FromLong(file_count
);
5281 if (procObj
&& hProcessObj
&& intObj
) {
5282 PyList_SetItem(procObj
,0,hProcessObj
);
5283 PyList_SetItem(procObj
,1,intObj
);
5285 fileObj
[0] = PyLong_FromVoidPtr(f1
);
5287 ins_rc
[0] = PyDict_SetItem(_PyPopenProcs
,
5291 if (file_count
>= 2) {
5292 fileObj
[1] = PyLong_FromVoidPtr(f2
);
5294 ins_rc
[1] = PyDict_SetItem(_PyPopenProcs
,
5299 if (file_count
>= 3) {
5300 fileObj
[2] = PyLong_FromVoidPtr(f3
);
5302 ins_rc
[2] = PyDict_SetItem(_PyPopenProcs
,
5308 if (ins_rc
[0] < 0 || !fileObj
[0] ||
5309 ins_rc
[1] < 0 || (file_count
> 1 && !fileObj
[1]) ||
5310 ins_rc
[2] < 0 || (file_count
> 2 && !fileObj
[2])) {
5311 /* Something failed - remove any dictionary
5312 * entries that did make it.
5314 if (!ins_rc
[0] && fileObj
[0]) {
5315 PyDict_DelItem(_PyPopenProcs
,
5318 if (!ins_rc
[1] && fileObj
[1]) {
5319 PyDict_DelItem(_PyPopenProcs
,
5322 if (!ins_rc
[2] && fileObj
[2]) {
5323 PyDict_DelItem(_PyPopenProcs
,
5330 * Clean up our localized references for the dictionary keys
5331 * and value since PyDict_SetItem will Py_INCREF any copies
5332 * that got placed in the dictionary.
5334 Py_XDECREF(procObj
);
5335 Py_XDECREF(fileObj
[0]);
5336 Py_XDECREF(fileObj
[1]);
5337 Py_XDECREF(fileObj
[2]);
5340 /* Child is launched. Close the parents copy of those pipe
5341 * handles that only the child should have open. You need to
5342 * make sure that no handles to the write end of the output pipe
5343 * are maintained in this process or else the pipe will not close
5344 * when the child process exits and the ReadFile will hang. */
5346 if (!CloseHandle(hChildStdinRd
))
5347 return win32_error("CloseHandle", NULL
);
5349 if (!CloseHandle(hChildStdoutWr
))
5350 return win32_error("CloseHandle", NULL
);
5352 if ((n
!= 4) && (!CloseHandle(hChildStderrWr
)))
5353 return win32_error("CloseHandle", NULL
);
5359 * Wrapper for fclose() to use for popen* files, so we can retrieve the
5360 * exit code for the child process and return as a result of the close.
5362 * This function uses the _PyPopenProcs dictionary in order to map the
5363 * input file pointer to information about the process that was
5364 * originally created by the popen* call that created the file pointer.
5365 * The dictionary uses the file pointer as a key (with one entry
5366 * inserted for each file returned by the original popen* call) and a
5367 * single list object as the value for all files from a single call.
5368 * The list object contains the Win32 process handle at [0], and a file
5369 * count at [1], which is initialized to the total number of file
5370 * handles using that list.
5372 * This function closes whichever handle it is passed, and decrements
5373 * the file count in the dictionary for the process handle pointed to
5374 * by this file. On the last close (when the file count reaches zero),
5375 * this function will wait for the child process and then return its
5376 * exit code as the result of the close() operation. This permits the
5377 * files to be closed in any order - it is always the close() of the
5378 * final handle that will return the exit code.
5380 * NOTE: This function is currently called with the GIL released.
5381 * hence we use the GILState API to manage our state.
5384 static int _PyPclose(FILE *file
)
5389 PyObject
*procObj
, *hProcessObj
, *intObj
, *fileObj
;
5392 PyGILState_STATE state
;
5395 /* Close the file handle first, to ensure it can't block the
5396 * child from exiting if it's the last handle.
5398 result
= fclose(file
);
5400 state
= PyGILState_Ensure();
5402 if (_PyPopenProcs
) {
5403 if ((fileObj
= PyLong_FromVoidPtr(file
)) != NULL
&&
5404 (procObj
= PyDict_GetItem(_PyPopenProcs
,
5405 fileObj
)) != NULL
&&
5406 (hProcessObj
= PyList_GetItem(procObj
,0)) != NULL
&&
5407 (intObj
= PyList_GetItem(procObj
,1)) != NULL
) {
5409 hProcess
= PyLong_AsVoidPtr(hProcessObj
);
5410 file_count
= PyInt_AsLong(intObj
);
5412 if (file_count
> 1) {
5413 /* Still other files referencing process */
5415 PyList_SetItem(procObj
,1,
5416 PyInt_FromLong(file_count
));
5418 /* Last file for this process */
5419 if (result
!= EOF
&&
5420 WaitForSingleObject(hProcess
, INFINITE
) != WAIT_FAILED
&&
5421 GetExitCodeProcess(hProcess
, &exit_code
)) {
5422 /* Possible truncation here in 16-bit environments, but
5423 * real exit codes are just the lower byte in any event.
5427 /* Indicate failure - this will cause the file object
5428 * to raise an I/O error and translate the last Win32
5429 * error code from errno. We do have a problem with
5430 * last errors that overlap the normal errno table,
5431 * but that's a consistent problem with the file object.
5433 if (result
!= EOF
) {
5434 /* If the error wasn't from the fclose(), then
5435 * set errno for the file object error handling.
5437 errno
= GetLastError();
5442 /* Free up the native handle at this point */
5443 CloseHandle(hProcess
);
5446 /* Remove this file pointer from dictionary */
5447 PyDict_DelItem(_PyPopenProcs
, fileObj
);
5449 if (PyDict_Size(_PyPopenProcs
) == 0) {
5450 Py_DECREF(_PyPopenProcs
);
5451 _PyPopenProcs
= NULL
;
5454 } /* if object retrieval ok */
5456 Py_XDECREF(fileObj
);
5457 } /* if _PyPopenProcs */
5460 PyGILState_Release(state
);
5465 #else /* which OS? */
5467 posix_popen(PyObject
*self
, PyObject
*args
)
5474 if (!PyArg_ParseTuple(args
, "s|si:popen", &name
, &mode
, &bufsize
))
5476 /* Strip mode of binary or text modifiers */
5477 if (strcmp(mode
, "rb") == 0 || strcmp(mode
, "rt") == 0)
5479 else if (strcmp(mode
, "wb") == 0 || strcmp(mode
, "wt") == 0)
5481 Py_BEGIN_ALLOW_THREADS
5482 fp
= popen(name
, mode
);
5483 Py_END_ALLOW_THREADS
5485 return posix_error();
5486 f
= PyFile_FromFile(fp
, name
, mode
, pclose
);
5488 PyFile_SetBufSize(f
, bufsize
);
5492 #endif /* PYOS_??? */
5493 #endif /* HAVE_POPEN */
5497 PyDoc_STRVAR(posix_setuid__doc__
,
5499 Set the current process's user id.");
5502 posix_setuid(PyObject
*self
, PyObject
*args
)
5505 if (!PyArg_ParseTuple(args
, "i:setuid", &uid
))
5507 if (setuid(uid
) < 0)
5508 return posix_error();
5512 #endif /* HAVE_SETUID */
5516 PyDoc_STRVAR(posix_seteuid__doc__
,
5518 Set the current process's effective user id.");
5521 posix_seteuid (PyObject
*self
, PyObject
*args
)
5524 if (!PyArg_ParseTuple(args
, "i", &euid
)) {
5526 } else if (seteuid(euid
) < 0) {
5527 return posix_error();
5533 #endif /* HAVE_SETEUID */
5536 PyDoc_STRVAR(posix_setegid__doc__
,
5538 Set the current process's effective group id.");
5541 posix_setegid (PyObject
*self
, PyObject
*args
)
5544 if (!PyArg_ParseTuple(args
, "i", &egid
)) {
5546 } else if (setegid(egid
) < 0) {
5547 return posix_error();
5553 #endif /* HAVE_SETEGID */
5555 #ifdef HAVE_SETREUID
5556 PyDoc_STRVAR(posix_setreuid__doc__
,
5557 "setreuid(ruid, euid)\n\n\
5558 Set the current process's real and effective user ids.");
5561 posix_setreuid (PyObject
*self
, PyObject
*args
)
5564 if (!PyArg_ParseTuple(args
, "ii", &ruid
, &euid
)) {
5566 } else if (setreuid(ruid
, euid
) < 0) {
5567 return posix_error();
5573 #endif /* HAVE_SETREUID */
5575 #ifdef HAVE_SETREGID
5576 PyDoc_STRVAR(posix_setregid__doc__
,
5577 "setregid(rgid, egid)\n\n\
5578 Set the current process's real and effective group ids.");
5581 posix_setregid (PyObject
*self
, PyObject
*args
)
5584 if (!PyArg_ParseTuple(args
, "ii", &rgid
, &egid
)) {
5586 } else if (setregid(rgid
, egid
) < 0) {
5587 return posix_error();
5593 #endif /* HAVE_SETREGID */
5596 PyDoc_STRVAR(posix_setgid__doc__
,
5598 Set the current process's group id.");
5601 posix_setgid(PyObject
*self
, PyObject
*args
)
5604 if (!PyArg_ParseTuple(args
, "i:setgid", &gid
))
5606 if (setgid(gid
) < 0)
5607 return posix_error();
5611 #endif /* HAVE_SETGID */
5613 #ifdef HAVE_SETGROUPS
5614 PyDoc_STRVAR(posix_setgroups__doc__
,
5615 "setgroups(list)\n\n\
5616 Set the groups of the current process to list.");
5619 posix_setgroups(PyObject
*self
, PyObject
*groups
)
5622 gid_t grouplist
[MAX_GROUPS
];
5624 if (!PySequence_Check(groups
)) {
5625 PyErr_SetString(PyExc_TypeError
, "setgroups argument must be a sequence");
5628 len
= PySequence_Size(groups
);
5629 if (len
> MAX_GROUPS
) {
5630 PyErr_SetString(PyExc_ValueError
, "too many groups");
5633 for(i
= 0; i
< len
; i
++) {
5635 elem
= PySequence_GetItem(groups
, i
);
5638 if (!PyInt_Check(elem
)) {
5639 if (!PyLong_Check(elem
)) {
5640 PyErr_SetString(PyExc_TypeError
,
5641 "groups must be integers");
5645 unsigned long x
= PyLong_AsUnsignedLong(elem
);
5646 if (PyErr_Occurred()) {
5647 PyErr_SetString(PyExc_TypeError
,
5648 "group id too big");
5653 /* read back the value to see if it fitted in gid_t */
5654 if (grouplist
[i
] != x
) {
5655 PyErr_SetString(PyExc_TypeError
,
5656 "group id too big");
5662 long x
= PyInt_AsLong(elem
);
5664 if (grouplist
[i
] != x
) {
5665 PyErr_SetString(PyExc_TypeError
,
5666 "group id too big");
5674 if (setgroups(len
, grouplist
) < 0)
5675 return posix_error();
5679 #endif /* HAVE_SETGROUPS */
5681 #if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
5683 wait_helper(pid_t pid
, int status
, struct rusage
*ru
)
5686 static PyObject
*struct_rusage
;
5689 return posix_error();
5691 if (struct_rusage
== NULL
) {
5692 PyObject
*m
= PyImport_ImportModuleNoBlock("resource");
5695 struct_rusage
= PyObject_GetAttrString(m
, "struct_rusage");
5697 if (struct_rusage
== NULL
)
5701 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
5702 result
= PyStructSequence_New((PyTypeObject
*) struct_rusage
);
5707 #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
5710 PyStructSequence_SET_ITEM(result
, 0,
5711 PyFloat_FromDouble(doubletime(ru
->ru_utime
)));
5712 PyStructSequence_SET_ITEM(result
, 1,
5713 PyFloat_FromDouble(doubletime(ru
->ru_stime
)));
5714 #define SET_INT(result, index, value)\
5715 PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value))
5716 SET_INT(result
, 2, ru
->ru_maxrss
);
5717 SET_INT(result
, 3, ru
->ru_ixrss
);
5718 SET_INT(result
, 4, ru
->ru_idrss
);
5719 SET_INT(result
, 5, ru
->ru_isrss
);
5720 SET_INT(result
, 6, ru
->ru_minflt
);
5721 SET_INT(result
, 7, ru
->ru_majflt
);
5722 SET_INT(result
, 8, ru
->ru_nswap
);
5723 SET_INT(result
, 9, ru
->ru_inblock
);
5724 SET_INT(result
, 10, ru
->ru_oublock
);
5725 SET_INT(result
, 11, ru
->ru_msgsnd
);
5726 SET_INT(result
, 12, ru
->ru_msgrcv
);
5727 SET_INT(result
, 13, ru
->ru_nsignals
);
5728 SET_INT(result
, 14, ru
->ru_nvcsw
);
5729 SET_INT(result
, 15, ru
->ru_nivcsw
);
5732 if (PyErr_Occurred()) {
5737 return Py_BuildValue("iiN", pid
, status
, result
);
5739 #endif /* HAVE_WAIT3 || HAVE_WAIT4 */
5742 PyDoc_STRVAR(posix_wait3__doc__
,
5743 "wait3(options) -> (pid, status, rusage)\n\n\
5744 Wait for completion of a child process.");
5747 posix_wait3(PyObject
*self
, PyObject
*args
)
5753 WAIT_STATUS_INT(status
) = 0;
5755 if (!PyArg_ParseTuple(args
, "i:wait3", &options
))
5758 Py_BEGIN_ALLOW_THREADS
5759 pid
= wait3(&status
, options
, &ru
);
5760 Py_END_ALLOW_THREADS
5762 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5764 #endif /* HAVE_WAIT3 */
5767 PyDoc_STRVAR(posix_wait4__doc__
,
5768 "wait4(pid, options) -> (pid, status, rusage)\n\n\
5769 Wait for completion of a given child process.");
5772 posix_wait4(PyObject
*self
, PyObject
*args
)
5778 WAIT_STATUS_INT(status
) = 0;
5780 if (!PyArg_ParseTuple(args
, "ii:wait4", &pid
, &options
))
5783 Py_BEGIN_ALLOW_THREADS
5784 pid
= wait4(pid
, &status
, options
, &ru
);
5785 Py_END_ALLOW_THREADS
5787 return wait_helper(pid
, WAIT_STATUS_INT(status
), &ru
);
5789 #endif /* HAVE_WAIT4 */
5792 PyDoc_STRVAR(posix_waitpid__doc__
,
5793 "waitpid(pid, options) -> (pid, status)\n\n\
5794 Wait for completion of a given child process.");
5797 posix_waitpid(PyObject
*self
, PyObject
*args
)
5802 WAIT_STATUS_INT(status
) = 0;
5804 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5806 Py_BEGIN_ALLOW_THREADS
5807 pid
= waitpid(pid
, &status
, options
);
5808 Py_END_ALLOW_THREADS
5810 return posix_error();
5812 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5815 #elif defined(HAVE_CWAIT)
5817 /* MS C has a variant of waitpid() that's usable for most purposes. */
5818 PyDoc_STRVAR(posix_waitpid__doc__
,
5819 "waitpid(pid, options) -> (pid, status << 8)\n\n"
5820 "Wait for completion of a given process. options is ignored on Windows.");
5823 posix_waitpid(PyObject
*self
, PyObject
*args
)
5826 int status
, options
;
5828 if (!PyArg_ParseTuple(args
, "ii:waitpid", &pid
, &options
))
5830 Py_BEGIN_ALLOW_THREADS
5831 pid
= _cwait(&status
, pid
, options
);
5832 Py_END_ALLOW_THREADS
5834 return posix_error();
5836 /* shift the status left a byte so this is more like the POSIX waitpid */
5837 return Py_BuildValue("ii", pid
, status
<< 8);
5839 #endif /* HAVE_WAITPID || HAVE_CWAIT */
5842 PyDoc_STRVAR(posix_wait__doc__
,
5843 "wait() -> (pid, status)\n\n\
5844 Wait for completion of a child process.");
5847 posix_wait(PyObject
*self
, PyObject
*noargs
)
5851 WAIT_STATUS_INT(status
) = 0;
5853 Py_BEGIN_ALLOW_THREADS
5854 pid
= wait(&status
);
5855 Py_END_ALLOW_THREADS
5857 return posix_error();
5859 return Py_BuildValue("ii", pid
, WAIT_STATUS_INT(status
));
5864 PyDoc_STRVAR(posix_lstat__doc__
,
5865 "lstat(path) -> stat result\n\n\
5866 Like stat(path), but do not follow symbolic links.");
5869 posix_lstat(PyObject
*self
, PyObject
*args
)
5872 return posix_do_stat(self
, args
, "et:lstat", lstat
, NULL
, NULL
);
5873 #else /* !HAVE_LSTAT */
5875 return posix_do_stat(self
, args
, "et:lstat", STAT
, "U:lstat", win32_wstat
);
5877 return posix_do_stat(self
, args
, "et:lstat", STAT
, NULL
, NULL
);
5879 #endif /* !HAVE_LSTAT */
5883 #ifdef HAVE_READLINK
5884 PyDoc_STRVAR(posix_readlink__doc__
,
5885 "readlink(path) -> path\n\n\
5886 Return a string representing the path to which the symbolic link points.");
5889 posix_readlink(PyObject
*self
, PyObject
*args
)
5892 char buf
[MAXPATHLEN
];
5895 #ifdef Py_USING_UNICODE
5896 int arg_is_unicode
= 0;
5899 if (!PyArg_ParseTuple(args
, "et:readlink",
5900 Py_FileSystemDefaultEncoding
, &path
))
5902 #ifdef Py_USING_UNICODE
5903 v
= PySequence_GetItem(args
, 0);
5909 if (PyUnicode_Check(v
)) {
5915 Py_BEGIN_ALLOW_THREADS
5916 n
= readlink(path
, buf
, (int) sizeof buf
);
5917 Py_END_ALLOW_THREADS
5919 return posix_error_with_allocated_filename(path
);
5922 v
= PyString_FromStringAndSize(buf
, n
);
5923 #ifdef Py_USING_UNICODE
5924 if (arg_is_unicode
) {
5927 w
= PyUnicode_FromEncodedObject(v
,
5928 Py_FileSystemDefaultEncoding
,
5935 /* fall back to the original byte string, as
5936 discussed in patch #683592 */
5943 #endif /* HAVE_READLINK */
5947 PyDoc_STRVAR(posix_symlink__doc__
,
5948 "symlink(src, dst)\n\n\
5949 Create a symbolic link pointing to src named dst.");
5952 posix_symlink(PyObject
*self
, PyObject
*args
)
5954 return posix_2str(args
, "etet:symlink", symlink
);
5956 #endif /* HAVE_SYMLINK */
5960 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
5966 Py_BEGIN_ALLOW_THREADS
5967 DosQuerySysInfo(QSV_MS_COUNT
, QSV_MS_COUNT
, &value
, sizeof(value
));
5968 Py_END_ALLOW_THREADS
5974 posix_times(PyObject
*self
, PyObject
*noargs
)
5976 /* Currently Only Uptime is Provided -- Others Later */
5977 return Py_BuildValue("ddddd",
5978 (double)0 /* t.tms_utime / HZ */,
5979 (double)0 /* t.tms_stime / HZ */,
5980 (double)0 /* t.tms_cutime / HZ */,
5981 (double)0 /* t.tms_cstime / HZ */,
5982 (double)system_uptime() / 1000);
5985 #define NEED_TICKS_PER_SECOND
5986 static long ticks_per_second
= -1;
5988 posix_times(PyObject
*self
, PyObject
*noargs
)
5994 if (c
== (clock_t) -1)
5995 return posix_error();
5996 return Py_BuildValue("ddddd",
5997 (double)t
.tms_utime
/ ticks_per_second
,
5998 (double)t
.tms_stime
/ ticks_per_second
,
5999 (double)t
.tms_cutime
/ ticks_per_second
,
6000 (double)t
.tms_cstime
/ ticks_per_second
,
6001 (double)c
/ ticks_per_second
);
6003 #endif /* not OS2 */
6004 #endif /* HAVE_TIMES */
6008 #define HAVE_TIMES /* so the method table will pick it up */
6010 posix_times(PyObject
*self
, PyObject
*noargs
)
6012 FILETIME create
, exit
, kernel
, user
;
6014 hProc
= GetCurrentProcess();
6015 GetProcessTimes(hProc
, &create
, &exit
, &kernel
, &user
);
6016 /* The fields of a FILETIME structure are the hi and lo part
6017 of a 64-bit value expressed in 100 nanosecond units.
6018 1e7 is one second in such units; 1e-7 the inverse.
6019 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
6021 return Py_BuildValue(
6023 (double)(user
.dwHighDateTime
*429.4967296 +
6024 user
.dwLowDateTime
*1e-7),
6025 (double)(kernel
.dwHighDateTime
*429.4967296 +
6026 kernel
.dwLowDateTime
*1e-7),
6031 #endif /* MS_WINDOWS */
6034 PyDoc_STRVAR(posix_times__doc__
,
6035 "times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n\
6036 Return a tuple of floating point numbers indicating process times.");
6041 PyDoc_STRVAR(posix_getsid__doc__
,
6042 "getsid(pid) -> sid\n\n\
6043 Call the system call getsid().");
6046 posix_getsid(PyObject
*self
, PyObject
*args
)
6050 if (!PyArg_ParseTuple(args
, "i:getsid", &pid
))
6054 return posix_error();
6055 return PyInt_FromLong((long)sid
);
6057 #endif /* HAVE_GETSID */
6061 PyDoc_STRVAR(posix_setsid__doc__
,
6063 Call the system call setsid().");
6066 posix_setsid(PyObject
*self
, PyObject
*noargs
)
6069 return posix_error();
6073 #endif /* HAVE_SETSID */
6076 PyDoc_STRVAR(posix_setpgid__doc__
,
6077 "setpgid(pid, pgrp)\n\n\
6078 Call the system call setpgid().");
6081 posix_setpgid(PyObject
*self
, PyObject
*args
)
6085 if (!PyArg_ParseTuple(args
, "ii:setpgid", &pid
, &pgrp
))
6087 if (setpgid(pid
, pgrp
) < 0)
6088 return posix_error();
6092 #endif /* HAVE_SETPGID */
6095 #ifdef HAVE_TCGETPGRP
6096 PyDoc_STRVAR(posix_tcgetpgrp__doc__
,
6097 "tcgetpgrp(fd) -> pgid\n\n\
6098 Return the process group associated with the terminal given by a fd.");
6101 posix_tcgetpgrp(PyObject
*self
, PyObject
*args
)
6105 if (!PyArg_ParseTuple(args
, "i:tcgetpgrp", &fd
))
6107 pgid
= tcgetpgrp(fd
);
6109 return posix_error();
6110 return PyInt_FromLong((long)pgid
);
6112 #endif /* HAVE_TCGETPGRP */
6115 #ifdef HAVE_TCSETPGRP
6116 PyDoc_STRVAR(posix_tcsetpgrp__doc__
,
6117 "tcsetpgrp(fd, pgid)\n\n\
6118 Set the process group associated with the terminal given by a fd.");
6121 posix_tcsetpgrp(PyObject
*self
, PyObject
*args
)
6124 if (!PyArg_ParseTuple(args
, "ii:tcsetpgrp", &fd
, &pgid
))
6126 if (tcsetpgrp(fd
, pgid
) < 0)
6127 return posix_error();
6131 #endif /* HAVE_TCSETPGRP */
6133 /* Functions acting on file descriptors */
6135 PyDoc_STRVAR(posix_open__doc__
,
6136 "open(filename, flag [, mode=0777]) -> fd\n\n\
6137 Open a file (for low level IO).");
6140 posix_open(PyObject
*self
, PyObject
*args
)
6148 if (unicode_file_names()) {
6149 PyUnicodeObject
*po
;
6150 if (PyArg_ParseTuple(args
, "Ui|i:mkdir", &po
, &flag
, &mode
)) {
6151 Py_BEGIN_ALLOW_THREADS
6152 /* PyUnicode_AS_UNICODE OK without thread
6153 lock as it is a simple dereference. */
6154 fd
= _wopen(PyUnicode_AS_UNICODE(po
), flag
, mode
);
6155 Py_END_ALLOW_THREADS
6157 return posix_error();
6158 return PyInt_FromLong((long)fd
);
6160 /* Drop the argument parsing error as narrow strings
6166 if (!PyArg_ParseTuple(args
, "eti|i",
6167 Py_FileSystemDefaultEncoding
, &file
,
6171 Py_BEGIN_ALLOW_THREADS
6172 fd
= open(file
, flag
, mode
);
6173 Py_END_ALLOW_THREADS
6175 return posix_error_with_allocated_filename(file
);
6177 return PyInt_FromLong((long)fd
);
6181 PyDoc_STRVAR(posix_close__doc__
,
6183 Close a file descriptor (for low level IO).");
6186 posix_close(PyObject
*self
, PyObject
*args
)
6189 if (!PyArg_ParseTuple(args
, "i:close", &fd
))
6191 Py_BEGIN_ALLOW_THREADS
6193 Py_END_ALLOW_THREADS
6195 return posix_error();
6201 PyDoc_STRVAR(posix_closerange__doc__
,
6202 "closerange(fd_low, fd_high)\n\n\
6203 Closes all file descriptors in [fd_low, fd_high), ignoring errors.");
6206 posix_closerange(PyObject
*self
, PyObject
*args
)
6208 int fd_from
, fd_to
, i
;
6209 if (!PyArg_ParseTuple(args
, "ii:closerange", &fd_from
, &fd_to
))
6211 Py_BEGIN_ALLOW_THREADS
6212 for (i
= fd_from
; i
< fd_to
; i
++)
6214 Py_END_ALLOW_THREADS
6219 PyDoc_STRVAR(posix_dup__doc__
,
6220 "dup(fd) -> fd2\n\n\
6221 Return a duplicate of a file descriptor.");
6224 posix_dup(PyObject
*self
, PyObject
*args
)
6227 if (!PyArg_ParseTuple(args
, "i:dup", &fd
))
6229 Py_BEGIN_ALLOW_THREADS
6231 Py_END_ALLOW_THREADS
6233 return posix_error();
6234 return PyInt_FromLong((long)fd
);
6238 PyDoc_STRVAR(posix_dup2__doc__
,
6239 "dup2(old_fd, new_fd)\n\n\
6240 Duplicate file descriptor.");
6243 posix_dup2(PyObject
*self
, PyObject
*args
)
6246 if (!PyArg_ParseTuple(args
, "ii:dup2", &fd
, &fd2
))
6248 Py_BEGIN_ALLOW_THREADS
6249 res
= dup2(fd
, fd2
);
6250 Py_END_ALLOW_THREADS
6252 return posix_error();
6258 PyDoc_STRVAR(posix_lseek__doc__
,
6259 "lseek(fd, pos, how) -> newpos\n\n\
6260 Set the current position of a file descriptor.");
6263 posix_lseek(PyObject
*self
, PyObject
*args
)
6266 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6267 PY_LONG_LONG pos
, res
;
6272 if (!PyArg_ParseTuple(args
, "iOi:lseek", &fd
, &posobj
, &how
))
6275 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
6277 case 0: how
= SEEK_SET
; break;
6278 case 1: how
= SEEK_CUR
; break;
6279 case 2: how
= SEEK_END
; break;
6281 #endif /* SEEK_END */
6283 #if !defined(HAVE_LARGEFILE_SUPPORT)
6284 pos
= PyInt_AsLong(posobj
);
6286 pos
= PyLong_Check(posobj
) ?
6287 PyLong_AsLongLong(posobj
) : PyInt_AsLong(posobj
);
6289 if (PyErr_Occurred())
6292 Py_BEGIN_ALLOW_THREADS
6293 #if defined(MS_WIN64) || defined(MS_WINDOWS)
6294 res
= _lseeki64(fd
, pos
, how
);
6296 res
= lseek(fd
, pos
, how
);
6298 Py_END_ALLOW_THREADS
6300 return posix_error();
6302 #if !defined(HAVE_LARGEFILE_SUPPORT)
6303 return PyInt_FromLong(res
);
6305 return PyLong_FromLongLong(res
);
6310 PyDoc_STRVAR(posix_read__doc__
,
6311 "read(fd, buffersize) -> string\n\n\
6312 Read a file descriptor.");
6315 posix_read(PyObject
*self
, PyObject
*args
)
6319 if (!PyArg_ParseTuple(args
, "ii:read", &fd
, &size
))
6323 return posix_error();
6325 buffer
= PyString_FromStringAndSize((char *)NULL
, size
);
6328 Py_BEGIN_ALLOW_THREADS
6329 n
= read(fd
, PyString_AsString(buffer
), size
);
6330 Py_END_ALLOW_THREADS
6333 return posix_error();
6336 _PyString_Resize(&buffer
, n
);
6341 PyDoc_STRVAR(posix_write__doc__
,
6342 "write(fd, string) -> byteswritten\n\n\
6343 Write a string to a file descriptor.");
6346 posix_write(PyObject
*self
, PyObject
*args
)
6352 if (!PyArg_ParseTuple(args
, "is*:write", &fd
, &pbuf
))
6354 Py_BEGIN_ALLOW_THREADS
6355 size
= write(fd
, pbuf
.buf
, (size_t)pbuf
.len
);
6356 Py_END_ALLOW_THREADS
6357 PyBuffer_Release(&pbuf
);
6359 return posix_error();
6360 return PyInt_FromSsize_t(size
);
6364 PyDoc_STRVAR(posix_fstat__doc__
,
6365 "fstat(fd) -> stat result\n\n\
6366 Like stat(), but for an open file descriptor.");
6369 posix_fstat(PyObject
*self
, PyObject
*args
)
6374 if (!PyArg_ParseTuple(args
, "i:fstat", &fd
))
6377 /* on OpenVMS we must ensure that all bytes are written to the file */
6380 Py_BEGIN_ALLOW_THREADS
6381 res
= FSTAT(fd
, &st
);
6382 Py_END_ALLOW_THREADS
6385 return win32_error("fstat", NULL
);
6387 return posix_error();
6391 return _pystat_fromstructstat(&st
);
6395 PyDoc_STRVAR(posix_fdopen__doc__
,
6396 "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n\
6397 Return an open file object connected to a file descriptor.");
6400 posix_fdopen(PyObject
*self
, PyObject
*args
)
6403 char *orgmode
= "r";
6408 if (!PyArg_ParseTuple(args
, "i|si", &fd
, &orgmode
, &bufsize
))
6411 /* Sanitize mode. See fileobject.c */
6412 mode
= PyMem_MALLOC(strlen(orgmode
)+3);
6417 strcpy(mode
, orgmode
);
6418 if (_PyFile_SanitizeMode(mode
)) {
6422 Py_BEGIN_ALLOW_THREADS
6423 #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H)
6424 if (mode
[0] == 'a') {
6425 /* try to make sure the O_APPEND flag is set */
6427 flags
= fcntl(fd
, F_GETFL
);
6429 fcntl(fd
, F_SETFL
, flags
| O_APPEND
);
6430 fp
= fdopen(fd
, mode
);
6431 if (fp
== NULL
&& flags
!= -1)
6432 /* restore old mode if fdopen failed */
6433 fcntl(fd
, F_SETFL
, flags
);
6435 fp
= fdopen(fd
, mode
);
6438 fp
= fdopen(fd
, mode
);
6440 Py_END_ALLOW_THREADS
6443 return posix_error();
6444 f
= PyFile_FromFile(fp
, "<fdopen>", orgmode
, fclose
);
6446 PyFile_SetBufSize(f
, bufsize
);
6450 PyDoc_STRVAR(posix_isatty__doc__
,
6451 "isatty(fd) -> bool\n\n\
6452 Return True if the file descriptor 'fd' is an open file descriptor\n\
6453 connected to the slave end of a terminal.");
6456 posix_isatty(PyObject
*self
, PyObject
*args
)
6459 if (!PyArg_ParseTuple(args
, "i:isatty", &fd
))
6461 return PyBool_FromLong(isatty(fd
));
6465 PyDoc_STRVAR(posix_pipe__doc__
,
6466 "pipe() -> (read_end, write_end)\n\n\
6470 posix_pipe(PyObject
*self
, PyObject
*noargs
)
6472 #if defined(PYOS_OS2)
6476 Py_BEGIN_ALLOW_THREADS
6477 rc
= DosCreatePipe( &read
, &write
, 4096);
6478 Py_END_ALLOW_THREADS
6480 return os2_error(rc
);
6482 return Py_BuildValue("(ii)", read
, write
);
6484 #if !defined(MS_WINDOWS)
6487 Py_BEGIN_ALLOW_THREADS
6489 Py_END_ALLOW_THREADS
6491 return posix_error();
6492 return Py_BuildValue("(ii)", fds
[0], fds
[1]);
6493 #else /* MS_WINDOWS */
6495 int read_fd
, write_fd
;
6497 Py_BEGIN_ALLOW_THREADS
6498 ok
= CreatePipe(&read
, &write
, NULL
, 0);
6499 Py_END_ALLOW_THREADS
6501 return win32_error("CreatePipe", NULL
);
6502 read_fd
= _open_osfhandle((Py_intptr_t
)read
, 0);
6503 write_fd
= _open_osfhandle((Py_intptr_t
)write
, 1);
6504 return Py_BuildValue("(ii)", read_fd
, write_fd
);
6505 #endif /* MS_WINDOWS */
6508 #endif /* HAVE_PIPE */
6512 PyDoc_STRVAR(posix_mkfifo__doc__
,
6513 "mkfifo(filename [, mode=0666])\n\n\
6514 Create a FIFO (a POSIX named pipe).");
6517 posix_mkfifo(PyObject
*self
, PyObject
*args
)
6522 if (!PyArg_ParseTuple(args
, "s|i:mkfifo", &filename
, &mode
))
6524 Py_BEGIN_ALLOW_THREADS
6525 res
= mkfifo(filename
, mode
);
6526 Py_END_ALLOW_THREADS
6528 return posix_error();
6535 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
6536 PyDoc_STRVAR(posix_mknod__doc__
,
6537 "mknod(filename [, mode=0600, device])\n\n\
6538 Create a filesystem node (file, device special file or named pipe)\n\
6539 named filename. mode specifies both the permissions to use and the\n\
6540 type of node to be created, being combined (bitwise OR) with one of\n\
6541 S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. For S_IFCHR and S_IFBLK,\n\
6542 device defines the newly created device special file (probably using\n\
6543 os.makedev()), otherwise it is ignored.");
6547 posix_mknod(PyObject
*self
, PyObject
*args
)
6553 if (!PyArg_ParseTuple(args
, "s|ii:mknod", &filename
, &mode
, &device
))
6555 Py_BEGIN_ALLOW_THREADS
6556 res
= mknod(filename
, mode
, device
);
6557 Py_END_ALLOW_THREADS
6559 return posix_error();
6565 #ifdef HAVE_DEVICE_MACROS
6566 PyDoc_STRVAR(posix_major__doc__
,
6567 "major(device) -> major number\n\
6568 Extracts a device major number from a raw device number.");
6571 posix_major(PyObject
*self
, PyObject
*args
)
6574 if (!PyArg_ParseTuple(args
, "i:major", &device
))
6576 return PyInt_FromLong((long)major(device
));
6579 PyDoc_STRVAR(posix_minor__doc__
,
6580 "minor(device) -> minor number\n\
6581 Extracts a device minor number from a raw device number.");
6584 posix_minor(PyObject
*self
, PyObject
*args
)
6587 if (!PyArg_ParseTuple(args
, "i:minor", &device
))
6589 return PyInt_FromLong((long)minor(device
));
6592 PyDoc_STRVAR(posix_makedev__doc__
,
6593 "makedev(major, minor) -> device number\n\
6594 Composes a raw device number from the major and minor device numbers.");
6597 posix_makedev(PyObject
*self
, PyObject
*args
)
6600 if (!PyArg_ParseTuple(args
, "ii:makedev", &major
, &minor
))
6602 return PyInt_FromLong((long)makedev(major
, minor
));
6604 #endif /* device macros */
6607 #ifdef HAVE_FTRUNCATE
6608 PyDoc_STRVAR(posix_ftruncate__doc__
,
6609 "ftruncate(fd, length)\n\n\
6610 Truncate a file to a specified length.");
6613 posix_ftruncate(PyObject
*self
, PyObject
*args
)
6620 if (!PyArg_ParseTuple(args
, "iO:ftruncate", &fd
, &lenobj
))
6623 #if !defined(HAVE_LARGEFILE_SUPPORT)
6624 length
= PyInt_AsLong(lenobj
);
6626 length
= PyLong_Check(lenobj
) ?
6627 PyLong_AsLongLong(lenobj
) : PyInt_AsLong(lenobj
);
6629 if (PyErr_Occurred())
6632 Py_BEGIN_ALLOW_THREADS
6633 res
= ftruncate(fd
, length
);
6634 Py_END_ALLOW_THREADS
6636 PyErr_SetFromErrno(PyExc_IOError
);
6645 PyDoc_STRVAR(posix_putenv__doc__
,
6646 "putenv(key, value)\n\n\
6647 Change or add an environment variable.");
6649 /* Save putenv() parameters as values here, so we can collect them when they
6650 * get re-set with another call for the same key. */
6651 static PyObject
*posix_putenv_garbage
;
6654 posix_putenv(PyObject
*self
, PyObject
*args
)
6661 if (!PyArg_ParseTuple(args
, "ss:putenv", &s1
, &s2
))
6664 #if defined(PYOS_OS2)
6665 if (stricmp(s1
, "BEGINLIBPATH") == 0) {
6668 rc
= DosSetExtLIBPATH(s2
, BEGIN_LIBPATH
);
6670 return os2_error(rc
);
6672 } else if (stricmp(s1
, "ENDLIBPATH") == 0) {
6675 rc
= DosSetExtLIBPATH(s2
, END_LIBPATH
);
6677 return os2_error(rc
);
6681 /* XXX This can leak memory -- not easy to fix :-( */
6682 len
= strlen(s1
) + strlen(s2
) + 2;
6683 /* len includes space for a trailing \0; the size arg to
6684 PyString_FromStringAndSize does not count that */
6685 newstr
= PyString_FromStringAndSize(NULL
, (int)len
- 1);
6687 return PyErr_NoMemory();
6688 newenv
= PyString_AS_STRING(newstr
);
6689 PyOS_snprintf(newenv
, len
, "%s=%s", s1
, s2
);
6690 if (putenv(newenv
)) {
6695 /* Install the first arg and newstr in posix_putenv_garbage;
6696 * this will cause previous value to be collected. This has to
6697 * happen after the real putenv() call because the old value
6698 * was still accessible until then. */
6699 if (PyDict_SetItem(posix_putenv_garbage
,
6700 PyTuple_GET_ITEM(args
, 0), newstr
)) {
6701 /* really not much we can do; just leak */
6708 #if defined(PYOS_OS2)
6716 #ifdef HAVE_UNSETENV
6717 PyDoc_STRVAR(posix_unsetenv__doc__
,
6719 Delete an environment variable.");
6722 posix_unsetenv(PyObject
*self
, PyObject
*args
)
6726 if (!PyArg_ParseTuple(args
, "s:unsetenv", &s1
))
6731 /* Remove the key from posix_putenv_garbage;
6732 * this will cause it to be collected. This has to
6733 * happen after the real unsetenv() call because the
6734 * old value was still accessible until then.
6736 if (PyDict_DelItem(posix_putenv_garbage
,
6737 PyTuple_GET_ITEM(args
, 0))) {
6738 /* really not much we can do; just leak */
6745 #endif /* unsetenv */
6747 PyDoc_STRVAR(posix_strerror__doc__
,
6748 "strerror(code) -> string\n\n\
6749 Translate an error code to a message string.");
6752 posix_strerror(PyObject
*self
, PyObject
*args
)
6756 if (!PyArg_ParseTuple(args
, "i:strerror", &code
))
6758 message
= strerror(code
);
6759 if (message
== NULL
) {
6760 PyErr_SetString(PyExc_ValueError
,
6761 "strerror() argument out of range");
6764 return PyString_FromString(message
);
6768 #ifdef HAVE_SYS_WAIT_H
6771 PyDoc_STRVAR(posix_WCOREDUMP__doc__
,
6772 "WCOREDUMP(status) -> bool\n\n\
6773 Return True if the process returning 'status' was dumped to a core file.");
6776 posix_WCOREDUMP(PyObject
*self
, PyObject
*args
)
6779 WAIT_STATUS_INT(status
) = 0;
6781 if (!PyArg_ParseTuple(args
, "i:WCOREDUMP", &WAIT_STATUS_INT(status
)))
6784 return PyBool_FromLong(WCOREDUMP(status
));
6786 #endif /* WCOREDUMP */
6789 PyDoc_STRVAR(posix_WIFCONTINUED__doc__
,
6790 "WIFCONTINUED(status) -> bool\n\n\
6791 Return True if the process returning 'status' was continued from a\n\
6792 job control stop.");
6795 posix_WIFCONTINUED(PyObject
*self
, PyObject
*args
)
6798 WAIT_STATUS_INT(status
) = 0;
6800 if (!PyArg_ParseTuple(args
, "i:WCONTINUED", &WAIT_STATUS_INT(status
)))
6803 return PyBool_FromLong(WIFCONTINUED(status
));
6805 #endif /* WIFCONTINUED */
6808 PyDoc_STRVAR(posix_WIFSTOPPED__doc__
,
6809 "WIFSTOPPED(status) -> bool\n\n\
6810 Return True if the process returning 'status' was stopped.");
6813 posix_WIFSTOPPED(PyObject
*self
, PyObject
*args
)
6816 WAIT_STATUS_INT(status
) = 0;
6818 if (!PyArg_ParseTuple(args
, "i:WIFSTOPPED", &WAIT_STATUS_INT(status
)))
6821 return PyBool_FromLong(WIFSTOPPED(status
));
6823 #endif /* WIFSTOPPED */
6826 PyDoc_STRVAR(posix_WIFSIGNALED__doc__
,
6827 "WIFSIGNALED(status) -> bool\n\n\
6828 Return True if the process returning 'status' was terminated by a signal.");
6831 posix_WIFSIGNALED(PyObject
*self
, PyObject
*args
)
6834 WAIT_STATUS_INT(status
) = 0;
6836 if (!PyArg_ParseTuple(args
, "i:WIFSIGNALED", &WAIT_STATUS_INT(status
)))
6839 return PyBool_FromLong(WIFSIGNALED(status
));
6841 #endif /* WIFSIGNALED */
6844 PyDoc_STRVAR(posix_WIFEXITED__doc__
,
6845 "WIFEXITED(status) -> bool\n\n\
6846 Return true if the process returning 'status' exited using the exit()\n\
6850 posix_WIFEXITED(PyObject
*self
, PyObject
*args
)
6853 WAIT_STATUS_INT(status
) = 0;
6855 if (!PyArg_ParseTuple(args
, "i:WIFEXITED", &WAIT_STATUS_INT(status
)))
6858 return PyBool_FromLong(WIFEXITED(status
));
6860 #endif /* WIFEXITED */
6863 PyDoc_STRVAR(posix_WEXITSTATUS__doc__
,
6864 "WEXITSTATUS(status) -> integer\n\n\
6865 Return the process return code from 'status'.");
6868 posix_WEXITSTATUS(PyObject
*self
, PyObject
*args
)
6871 WAIT_STATUS_INT(status
) = 0;
6873 if (!PyArg_ParseTuple(args
, "i:WEXITSTATUS", &WAIT_STATUS_INT(status
)))
6876 return Py_BuildValue("i", WEXITSTATUS(status
));
6878 #endif /* WEXITSTATUS */
6881 PyDoc_STRVAR(posix_WTERMSIG__doc__
,
6882 "WTERMSIG(status) -> integer\n\n\
6883 Return the signal that terminated the process that provided the 'status'\n\
6887 posix_WTERMSIG(PyObject
*self
, PyObject
*args
)
6890 WAIT_STATUS_INT(status
) = 0;
6892 if (!PyArg_ParseTuple(args
, "i:WTERMSIG", &WAIT_STATUS_INT(status
)))
6895 return Py_BuildValue("i", WTERMSIG(status
));
6897 #endif /* WTERMSIG */
6900 PyDoc_STRVAR(posix_WSTOPSIG__doc__
,
6901 "WSTOPSIG(status) -> integer\n\n\
6902 Return the signal that stopped the process that provided\n\
6903 the 'status' value.");
6906 posix_WSTOPSIG(PyObject
*self
, PyObject
*args
)
6909 WAIT_STATUS_INT(status
) = 0;
6911 if (!PyArg_ParseTuple(args
, "i:WSTOPSIG", &WAIT_STATUS_INT(status
)))
6914 return Py_BuildValue("i", WSTOPSIG(status
));
6916 #endif /* WSTOPSIG */
6918 #endif /* HAVE_SYS_WAIT_H */
6921 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
6923 /* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
6924 needed definitions in sys/statvfs.h */
6927 #include <sys/statvfs.h>
6930 _pystatvfs_fromstructstatvfs(struct statvfs st
) {
6931 PyObject
*v
= PyStructSequence_New(&StatVFSResultType
);
6935 #if !defined(HAVE_LARGEFILE_SUPPORT)
6936 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6937 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6938 PyStructSequence_SET_ITEM(v
, 2, PyInt_FromLong((long) st
.f_blocks
));
6939 PyStructSequence_SET_ITEM(v
, 3, PyInt_FromLong((long) st
.f_bfree
));
6940 PyStructSequence_SET_ITEM(v
, 4, PyInt_FromLong((long) st
.f_bavail
));
6941 PyStructSequence_SET_ITEM(v
, 5, PyInt_FromLong((long) st
.f_files
));
6942 PyStructSequence_SET_ITEM(v
, 6, PyInt_FromLong((long) st
.f_ffree
));
6943 PyStructSequence_SET_ITEM(v
, 7, PyInt_FromLong((long) st
.f_favail
));
6944 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6945 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6947 PyStructSequence_SET_ITEM(v
, 0, PyInt_FromLong((long) st
.f_bsize
));
6948 PyStructSequence_SET_ITEM(v
, 1, PyInt_FromLong((long) st
.f_frsize
));
6949 PyStructSequence_SET_ITEM(v
, 2,
6950 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_blocks
));
6951 PyStructSequence_SET_ITEM(v
, 3,
6952 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bfree
));
6953 PyStructSequence_SET_ITEM(v
, 4,
6954 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_bavail
));
6955 PyStructSequence_SET_ITEM(v
, 5,
6956 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_files
));
6957 PyStructSequence_SET_ITEM(v
, 6,
6958 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_ffree
));
6959 PyStructSequence_SET_ITEM(v
, 7,
6960 PyLong_FromLongLong((PY_LONG_LONG
) st
.f_favail
));
6961 PyStructSequence_SET_ITEM(v
, 8, PyInt_FromLong((long) st
.f_flag
));
6962 PyStructSequence_SET_ITEM(v
, 9, PyInt_FromLong((long) st
.f_namemax
));
6968 PyDoc_STRVAR(posix_fstatvfs__doc__
,
6969 "fstatvfs(fd) -> statvfs result\n\n\
6970 Perform an fstatvfs system call on the given fd.");
6973 posix_fstatvfs(PyObject
*self
, PyObject
*args
)
6978 if (!PyArg_ParseTuple(args
, "i:fstatvfs", &fd
))
6980 Py_BEGIN_ALLOW_THREADS
6981 res
= fstatvfs(fd
, &st
);
6982 Py_END_ALLOW_THREADS
6984 return posix_error();
6986 return _pystatvfs_fromstructstatvfs(st
);
6988 #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */
6991 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
6992 #include <sys/statvfs.h>
6994 PyDoc_STRVAR(posix_statvfs__doc__
,
6995 "statvfs(path) -> statvfs result\n\n\
6996 Perform a statvfs system call on the given path.");
6999 posix_statvfs(PyObject
*self
, PyObject
*args
)
7004 if (!PyArg_ParseTuple(args
, "s:statvfs", &path
))
7006 Py_BEGIN_ALLOW_THREADS
7007 res
= statvfs(path
, &st
);
7008 Py_END_ALLOW_THREADS
7010 return posix_error_with_filename(path
);
7012 return _pystatvfs_fromstructstatvfs(st
);
7014 #endif /* HAVE_STATVFS */
7018 PyDoc_STRVAR(posix_tempnam__doc__
,
7019 "tempnam([dir[, prefix]]) -> string\n\n\
7020 Return a unique name for a temporary file.\n\
7021 The directory and a prefix may be specified as strings; they may be omitted\n\
7022 or None if not needed.");
7025 posix_tempnam(PyObject
*self
, PyObject
*args
)
7027 PyObject
*result
= NULL
;
7032 if (!PyArg_ParseTuple(args
, "|zz:tempnam", &dir
, &pfx
))
7035 if (PyErr_Warn(PyExc_RuntimeWarning
,
7036 "tempnam is a potential security risk to your program") < 0)
7040 name
= _tempnam(dir
, pfx
);
7042 name
= tempnam(dir
, pfx
);
7045 return PyErr_NoMemory();
7046 result
= PyString_FromString(name
);
7054 PyDoc_STRVAR(posix_tmpfile__doc__
,
7055 "tmpfile() -> file object\n\n\
7056 Create a temporary file with no directory entries.");
7059 posix_tmpfile(PyObject
*self
, PyObject
*noargs
)
7065 return posix_error();
7066 return PyFile_FromFile(fp
, "<tmpfile>", "w+b", fclose
);
7072 PyDoc_STRVAR(posix_tmpnam__doc__
,
7073 "tmpnam() -> string\n\n\
7074 Return a unique name for a temporary file.");
7077 posix_tmpnam(PyObject
*self
, PyObject
*noargs
)
7079 char buffer
[L_tmpnam
];
7082 if (PyErr_Warn(PyExc_RuntimeWarning
,
7083 "tmpnam is a potential security risk to your program") < 0)
7087 name
= tmpnam_r(buffer
);
7089 name
= tmpnam(buffer
);
7092 PyObject
*err
= Py_BuildValue("is", 0,
7094 "unexpected NULL from tmpnam_r"
7096 "unexpected NULL from tmpnam"
7099 PyErr_SetObject(PyExc_OSError
, err
);
7103 return PyString_FromString(buffer
);
7108 /* This is used for fpathconf(), pathconf(), confstr() and sysconf().
7109 * It maps strings representing configuration variable names to
7110 * integer values, allowing those functions to be called with the
7111 * magic names instead of polluting the module's namespace with tons of
7112 * rarely-used constants. There are three separate tables that use
7113 * these definitions.
7115 * This code is always included, even if none of the interfaces that
7116 * need it are included. The #if hackery needed to avoid it would be
7117 * sufficiently pervasive that it's not worth the loss of readability.
7125 conv_confname(PyObject
*arg
, int *valuep
, struct constdef
*table
,
7128 if (PyInt_Check(arg
)) {
7129 *valuep
= PyInt_AS_LONG(arg
);
7132 if (PyString_Check(arg
)) {
7133 /* look up the value in the table using a binary search */
7136 size_t hi
= tablesize
;
7138 char *confname
= PyString_AS_STRING(arg
);
7140 mid
= (lo
+ hi
) / 2;
7141 cmp
= strcmp(confname
, table
[mid
].name
);
7147 *valuep
= table
[mid
].value
;
7151 PyErr_SetString(PyExc_ValueError
, "unrecognized configuration name");
7154 PyErr_SetString(PyExc_TypeError
,
7155 "configuration names must be strings or integers");
7160 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
7161 static struct constdef posix_constants_pathconf
[] = {
7162 #ifdef _PC_ABI_AIO_XFER_MAX
7163 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX
},
7165 #ifdef _PC_ABI_ASYNC_IO
7166 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO
},
7169 {"PC_ASYNC_IO", _PC_ASYNC_IO
},
7171 #ifdef _PC_CHOWN_RESTRICTED
7172 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED
},
7174 #ifdef _PC_FILESIZEBITS
7175 {"PC_FILESIZEBITS", _PC_FILESIZEBITS
},
7178 {"PC_LAST", _PC_LAST
},
7181 {"PC_LINK_MAX", _PC_LINK_MAX
},
7183 #ifdef _PC_MAX_CANON
7184 {"PC_MAX_CANON", _PC_MAX_CANON
},
7186 #ifdef _PC_MAX_INPUT
7187 {"PC_MAX_INPUT", _PC_MAX_INPUT
},
7190 {"PC_NAME_MAX", _PC_NAME_MAX
},
7193 {"PC_NO_TRUNC", _PC_NO_TRUNC
},
7196 {"PC_PATH_MAX", _PC_PATH_MAX
},
7199 {"PC_PIPE_BUF", _PC_PIPE_BUF
},
7202 {"PC_PRIO_IO", _PC_PRIO_IO
},
7204 #ifdef _PC_SOCK_MAXBUF
7205 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF
},
7208 {"PC_SYNC_IO", _PC_SYNC_IO
},
7211 {"PC_VDISABLE", _PC_VDISABLE
},
7216 conv_path_confname(PyObject
*arg
, int *valuep
)
7218 return conv_confname(arg
, valuep
, posix_constants_pathconf
,
7219 sizeof(posix_constants_pathconf
)
7220 / sizeof(struct constdef
));
7224 #ifdef HAVE_FPATHCONF
7225 PyDoc_STRVAR(posix_fpathconf__doc__
,
7226 "fpathconf(fd, name) -> integer\n\n\
7227 Return the configuration limit name for the file descriptor fd.\n\
7228 If there is no limit, return -1.");
7231 posix_fpathconf(PyObject
*self
, PyObject
*args
)
7233 PyObject
*result
= NULL
;
7236 if (PyArg_ParseTuple(args
, "iO&:fpathconf", &fd
,
7237 conv_path_confname
, &name
)) {
7241 limit
= fpathconf(fd
, name
);
7242 if (limit
== -1 && errno
!= 0)
7245 result
= PyInt_FromLong(limit
);
7252 #ifdef HAVE_PATHCONF
7253 PyDoc_STRVAR(posix_pathconf__doc__
,
7254 "pathconf(path, name) -> integer\n\n\
7255 Return the configuration limit name for the file or directory path.\n\
7256 If there is no limit, return -1.");
7259 posix_pathconf(PyObject
*self
, PyObject
*args
)
7261 PyObject
*result
= NULL
;
7265 if (PyArg_ParseTuple(args
, "sO&:pathconf", &path
,
7266 conv_path_confname
, &name
)) {
7270 limit
= pathconf(path
, name
);
7271 if (limit
== -1 && errno
!= 0) {
7272 if (errno
== EINVAL
)
7273 /* could be a path or name problem */
7276 posix_error_with_filename(path
);
7279 result
= PyInt_FromLong(limit
);
7286 static struct constdef posix_constants_confstr
[] = {
7287 #ifdef _CS_ARCHITECTURE
7288 {"CS_ARCHITECTURE", _CS_ARCHITECTURE
},
7291 {"CS_HOSTNAME", _CS_HOSTNAME
},
7293 #ifdef _CS_HW_PROVIDER
7294 {"CS_HW_PROVIDER", _CS_HW_PROVIDER
},
7296 #ifdef _CS_HW_SERIAL
7297 {"CS_HW_SERIAL", _CS_HW_SERIAL
},
7299 #ifdef _CS_INITTAB_NAME
7300 {"CS_INITTAB_NAME", _CS_INITTAB_NAME
},
7302 #ifdef _CS_LFS64_CFLAGS
7303 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS
},
7305 #ifdef _CS_LFS64_LDFLAGS
7306 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS
},
7308 #ifdef _CS_LFS64_LIBS
7309 {"CS_LFS64_LIBS", _CS_LFS64_LIBS
},
7311 #ifdef _CS_LFS64_LINTFLAGS
7312 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS
},
7314 #ifdef _CS_LFS_CFLAGS
7315 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS
},
7317 #ifdef _CS_LFS_LDFLAGS
7318 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS
},
7321 {"CS_LFS_LIBS", _CS_LFS_LIBS
},
7323 #ifdef _CS_LFS_LINTFLAGS
7324 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS
},
7327 {"CS_MACHINE", _CS_MACHINE
},
7330 {"CS_PATH", _CS_PATH
},
7333 {"CS_RELEASE", _CS_RELEASE
},
7335 #ifdef _CS_SRPC_DOMAIN
7336 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN
},
7339 {"CS_SYSNAME", _CS_SYSNAME
},
7342 {"CS_VERSION", _CS_VERSION
},
7344 #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
7345 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS
},
7347 #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
7348 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS
},
7350 #ifdef _CS_XBS5_ILP32_OFF32_LIBS
7351 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS
},
7353 #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
7354 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS
},
7356 #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
7357 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS
},
7359 #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
7360 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS
},
7362 #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
7363 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS
},
7365 #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
7366 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
},
7368 #ifdef _CS_XBS5_LP64_OFF64_CFLAGS
7369 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS
},
7371 #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
7372 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS
},
7374 #ifdef _CS_XBS5_LP64_OFF64_LIBS
7375 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS
},
7377 #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
7378 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS
},
7380 #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
7381 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS
},
7383 #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
7384 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
},
7386 #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
7387 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS
},
7389 #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
7390 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
},
7392 #ifdef _MIPS_CS_AVAIL_PROCESSORS
7393 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS
},
7395 #ifdef _MIPS_CS_BASE
7396 {"MIPS_CS_BASE", _MIPS_CS_BASE
},
7398 #ifdef _MIPS_CS_HOSTID
7399 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID
},
7401 #ifdef _MIPS_CS_HW_NAME
7402 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME
},
7404 #ifdef _MIPS_CS_NUM_PROCESSORS
7405 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS
},
7407 #ifdef _MIPS_CS_OSREL_MAJ
7408 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ
},
7410 #ifdef _MIPS_CS_OSREL_MIN
7411 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN
},
7413 #ifdef _MIPS_CS_OSREL_PATCH
7414 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH
},
7416 #ifdef _MIPS_CS_OS_NAME
7417 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME
},
7419 #ifdef _MIPS_CS_OS_PROVIDER
7420 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER
},
7422 #ifdef _MIPS_CS_PROCESSORS
7423 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS
},
7425 #ifdef _MIPS_CS_SERIAL
7426 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL
},
7428 #ifdef _MIPS_CS_VENDOR
7429 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR
},
7434 conv_confstr_confname(PyObject
*arg
, int *valuep
)
7436 return conv_confname(arg
, valuep
, posix_constants_confstr
,
7437 sizeof(posix_constants_confstr
)
7438 / sizeof(struct constdef
));
7441 PyDoc_STRVAR(posix_confstr__doc__
,
7442 "confstr(name) -> string\n\n\
7443 Return a string-valued system configuration variable.");
7446 posix_confstr(PyObject
*self
, PyObject
*args
)
7448 PyObject
*result
= NULL
;
7452 if (PyArg_ParseTuple(args
, "O&:confstr", conv_confstr_confname
, &name
)) {
7456 len
= confstr(name
, buffer
, sizeof(buffer
));
7467 if ((unsigned int)len
>= sizeof(buffer
)) {
7468 result
= PyString_FromStringAndSize(NULL
, len
-1);
7470 confstr(name
, PyString_AS_STRING(result
), len
);
7473 result
= PyString_FromStringAndSize(buffer
, len
-1);
7482 static struct constdef posix_constants_sysconf
[] = {
7483 #ifdef _SC_2_CHAR_TERM
7484 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM
},
7487 {"SC_2_C_BIND", _SC_2_C_BIND
},
7490 {"SC_2_C_DEV", _SC_2_C_DEV
},
7492 #ifdef _SC_2_C_VERSION
7493 {"SC_2_C_VERSION", _SC_2_C_VERSION
},
7495 #ifdef _SC_2_FORT_DEV
7496 {"SC_2_FORT_DEV", _SC_2_FORT_DEV
},
7498 #ifdef _SC_2_FORT_RUN
7499 {"SC_2_FORT_RUN", _SC_2_FORT_RUN
},
7501 #ifdef _SC_2_LOCALEDEF
7502 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF
},
7505 {"SC_2_SW_DEV", _SC_2_SW_DEV
},
7508 {"SC_2_UPE", _SC_2_UPE
},
7510 #ifdef _SC_2_VERSION
7511 {"SC_2_VERSION", _SC_2_VERSION
},
7513 #ifdef _SC_ABI_ASYNCHRONOUS_IO
7514 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO
},
7517 {"SC_ACL", _SC_ACL
},
7519 #ifdef _SC_AIO_LISTIO_MAX
7520 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX
},
7523 {"SC_AIO_MAX", _SC_AIO_MAX
},
7525 #ifdef _SC_AIO_PRIO_DELTA_MAX
7526 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX
},
7529 {"SC_ARG_MAX", _SC_ARG_MAX
},
7531 #ifdef _SC_ASYNCHRONOUS_IO
7532 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO
},
7534 #ifdef _SC_ATEXIT_MAX
7535 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX
},
7538 {"SC_AUDIT", _SC_AUDIT
},
7540 #ifdef _SC_AVPHYS_PAGES
7541 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES
},
7543 #ifdef _SC_BC_BASE_MAX
7544 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX
},
7546 #ifdef _SC_BC_DIM_MAX
7547 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX
},
7549 #ifdef _SC_BC_SCALE_MAX
7550 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX
},
7552 #ifdef _SC_BC_STRING_MAX
7553 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX
},
7556 {"SC_CAP", _SC_CAP
},
7558 #ifdef _SC_CHARCLASS_NAME_MAX
7559 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX
},
7562 {"SC_CHAR_BIT", _SC_CHAR_BIT
},
7565 {"SC_CHAR_MAX", _SC_CHAR_MAX
},
7568 {"SC_CHAR_MIN", _SC_CHAR_MIN
},
7570 #ifdef _SC_CHILD_MAX
7571 {"SC_CHILD_MAX", _SC_CHILD_MAX
},
7574 {"SC_CLK_TCK", _SC_CLK_TCK
},
7576 #ifdef _SC_COHER_BLKSZ
7577 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ
},
7579 #ifdef _SC_COLL_WEIGHTS_MAX
7580 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX
},
7582 #ifdef _SC_DCACHE_ASSOC
7583 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC
},
7585 #ifdef _SC_DCACHE_BLKSZ
7586 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ
},
7588 #ifdef _SC_DCACHE_LINESZ
7589 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ
},
7591 #ifdef _SC_DCACHE_SZ
7592 {"SC_DCACHE_SZ", _SC_DCACHE_SZ
},
7594 #ifdef _SC_DCACHE_TBLKSZ
7595 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ
},
7597 #ifdef _SC_DELAYTIMER_MAX
7598 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX
},
7600 #ifdef _SC_EQUIV_CLASS_MAX
7601 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX
},
7603 #ifdef _SC_EXPR_NEST_MAX
7604 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX
},
7607 {"SC_FSYNC", _SC_FSYNC
},
7609 #ifdef _SC_GETGR_R_SIZE_MAX
7610 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX
},
7612 #ifdef _SC_GETPW_R_SIZE_MAX
7613 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX
},
7615 #ifdef _SC_ICACHE_ASSOC
7616 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC
},
7618 #ifdef _SC_ICACHE_BLKSZ
7619 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ
},
7621 #ifdef _SC_ICACHE_LINESZ
7622 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ
},
7624 #ifdef _SC_ICACHE_SZ
7625 {"SC_ICACHE_SZ", _SC_ICACHE_SZ
},
7628 {"SC_INF", _SC_INF
},
7631 {"SC_INT_MAX", _SC_INT_MAX
},
7634 {"SC_INT_MIN", _SC_INT_MIN
},
7637 {"SC_IOV_MAX", _SC_IOV_MAX
},
7639 #ifdef _SC_IP_SECOPTS
7640 {"SC_IP_SECOPTS", _SC_IP_SECOPTS
},
7642 #ifdef _SC_JOB_CONTROL
7643 {"SC_JOB_CONTROL", _SC_JOB_CONTROL
},
7645 #ifdef _SC_KERN_POINTERS
7646 {"SC_KERN_POINTERS", _SC_KERN_POINTERS
},
7649 {"SC_KERN_SIM", _SC_KERN_SIM
},
7652 {"SC_LINE_MAX", _SC_LINE_MAX
},
7654 #ifdef _SC_LOGIN_NAME_MAX
7655 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX
},
7657 #ifdef _SC_LOGNAME_MAX
7658 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX
},
7661 {"SC_LONG_BIT", _SC_LONG_BIT
},
7664 {"SC_MAC", _SC_MAC
},
7666 #ifdef _SC_MAPPED_FILES
7667 {"SC_MAPPED_FILES", _SC_MAPPED_FILES
},
7670 {"SC_MAXPID", _SC_MAXPID
},
7672 #ifdef _SC_MB_LEN_MAX
7673 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX
},
7676 {"SC_MEMLOCK", _SC_MEMLOCK
},
7678 #ifdef _SC_MEMLOCK_RANGE
7679 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE
},
7681 #ifdef _SC_MEMORY_PROTECTION
7682 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION
},
7684 #ifdef _SC_MESSAGE_PASSING
7685 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING
},
7687 #ifdef _SC_MMAP_FIXED_ALIGNMENT
7688 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT
},
7690 #ifdef _SC_MQ_OPEN_MAX
7691 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX
},
7693 #ifdef _SC_MQ_PRIO_MAX
7694 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX
},
7696 #ifdef _SC_NACLS_MAX
7697 {"SC_NACLS_MAX", _SC_NACLS_MAX
},
7699 #ifdef _SC_NGROUPS_MAX
7700 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX
},
7702 #ifdef _SC_NL_ARGMAX
7703 {"SC_NL_ARGMAX", _SC_NL_ARGMAX
},
7705 #ifdef _SC_NL_LANGMAX
7706 {"SC_NL_LANGMAX", _SC_NL_LANGMAX
},
7708 #ifdef _SC_NL_MSGMAX
7709 {"SC_NL_MSGMAX", _SC_NL_MSGMAX
},
7712 {"SC_NL_NMAX", _SC_NL_NMAX
},
7714 #ifdef _SC_NL_SETMAX
7715 {"SC_NL_SETMAX", _SC_NL_SETMAX
},
7717 #ifdef _SC_NL_TEXTMAX
7718 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX
},
7720 #ifdef _SC_NPROCESSORS_CONF
7721 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF
},
7723 #ifdef _SC_NPROCESSORS_ONLN
7724 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN
},
7726 #ifdef _SC_NPROC_CONF
7727 {"SC_NPROC_CONF", _SC_NPROC_CONF
},
7729 #ifdef _SC_NPROC_ONLN
7730 {"SC_NPROC_ONLN", _SC_NPROC_ONLN
},
7733 {"SC_NZERO", _SC_NZERO
},
7736 {"SC_OPEN_MAX", _SC_OPEN_MAX
},
7739 {"SC_PAGESIZE", _SC_PAGESIZE
},
7741 #ifdef _SC_PAGE_SIZE
7742 {"SC_PAGE_SIZE", _SC_PAGE_SIZE
},
7745 {"SC_PASS_MAX", _SC_PASS_MAX
},
7747 #ifdef _SC_PHYS_PAGES
7748 {"SC_PHYS_PAGES", _SC_PHYS_PAGES
},
7751 {"SC_PII", _SC_PII
},
7753 #ifdef _SC_PII_INTERNET
7754 {"SC_PII_INTERNET", _SC_PII_INTERNET
},
7756 #ifdef _SC_PII_INTERNET_DGRAM
7757 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM
},
7759 #ifdef _SC_PII_INTERNET_STREAM
7760 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM
},
7763 {"SC_PII_OSI", _SC_PII_OSI
},
7765 #ifdef _SC_PII_OSI_CLTS
7766 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS
},
7768 #ifdef _SC_PII_OSI_COTS
7769 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS
},
7771 #ifdef _SC_PII_OSI_M
7772 {"SC_PII_OSI_M", _SC_PII_OSI_M
},
7774 #ifdef _SC_PII_SOCKET
7775 {"SC_PII_SOCKET", _SC_PII_SOCKET
},
7778 {"SC_PII_XTI", _SC_PII_XTI
},
7781 {"SC_POLL", _SC_POLL
},
7783 #ifdef _SC_PRIORITIZED_IO
7784 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO
},
7786 #ifdef _SC_PRIORITY_SCHEDULING
7787 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING
},
7789 #ifdef _SC_REALTIME_SIGNALS
7790 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS
},
7792 #ifdef _SC_RE_DUP_MAX
7793 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX
},
7795 #ifdef _SC_RTSIG_MAX
7796 {"SC_RTSIG_MAX", _SC_RTSIG_MAX
},
7798 #ifdef _SC_SAVED_IDS
7799 {"SC_SAVED_IDS", _SC_SAVED_IDS
},
7801 #ifdef _SC_SCHAR_MAX
7802 {"SC_SCHAR_MAX", _SC_SCHAR_MAX
},
7804 #ifdef _SC_SCHAR_MIN
7805 {"SC_SCHAR_MIN", _SC_SCHAR_MIN
},
7808 {"SC_SELECT", _SC_SELECT
},
7810 #ifdef _SC_SEMAPHORES
7811 {"SC_SEMAPHORES", _SC_SEMAPHORES
},
7813 #ifdef _SC_SEM_NSEMS_MAX
7814 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX
},
7816 #ifdef _SC_SEM_VALUE_MAX
7817 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX
},
7819 #ifdef _SC_SHARED_MEMORY_OBJECTS
7820 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS
},
7823 {"SC_SHRT_MAX", _SC_SHRT_MAX
},
7826 {"SC_SHRT_MIN", _SC_SHRT_MIN
},
7828 #ifdef _SC_SIGQUEUE_MAX
7829 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX
},
7831 #ifdef _SC_SIGRT_MAX
7832 {"SC_SIGRT_MAX", _SC_SIGRT_MAX
},
7834 #ifdef _SC_SIGRT_MIN
7835 {"SC_SIGRT_MIN", _SC_SIGRT_MIN
},
7837 #ifdef _SC_SOFTPOWER
7838 {"SC_SOFTPOWER", _SC_SOFTPOWER
},
7840 #ifdef _SC_SPLIT_CACHE
7841 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE
},
7843 #ifdef _SC_SSIZE_MAX
7844 {"SC_SSIZE_MAX", _SC_SSIZE_MAX
},
7846 #ifdef _SC_STACK_PROT
7847 {"SC_STACK_PROT", _SC_STACK_PROT
},
7849 #ifdef _SC_STREAM_MAX
7850 {"SC_STREAM_MAX", _SC_STREAM_MAX
},
7852 #ifdef _SC_SYNCHRONIZED_IO
7853 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO
},
7856 {"SC_THREADS", _SC_THREADS
},
7858 #ifdef _SC_THREAD_ATTR_STACKADDR
7859 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR
},
7861 #ifdef _SC_THREAD_ATTR_STACKSIZE
7862 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE
},
7864 #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
7865 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS
},
7867 #ifdef _SC_THREAD_KEYS_MAX
7868 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX
},
7870 #ifdef _SC_THREAD_PRIORITY_SCHEDULING
7871 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING
},
7873 #ifdef _SC_THREAD_PRIO_INHERIT
7874 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT
},
7876 #ifdef _SC_THREAD_PRIO_PROTECT
7877 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT
},
7879 #ifdef _SC_THREAD_PROCESS_SHARED
7880 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED
},
7882 #ifdef _SC_THREAD_SAFE_FUNCTIONS
7883 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS
},
7885 #ifdef _SC_THREAD_STACK_MIN
7886 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN
},
7888 #ifdef _SC_THREAD_THREADS_MAX
7889 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX
},
7892 {"SC_TIMERS", _SC_TIMERS
},
7894 #ifdef _SC_TIMER_MAX
7895 {"SC_TIMER_MAX", _SC_TIMER_MAX
},
7897 #ifdef _SC_TTY_NAME_MAX
7898 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX
},
7900 #ifdef _SC_TZNAME_MAX
7901 {"SC_TZNAME_MAX", _SC_TZNAME_MAX
},
7903 #ifdef _SC_T_IOV_MAX
7904 {"SC_T_IOV_MAX", _SC_T_IOV_MAX
},
7906 #ifdef _SC_UCHAR_MAX
7907 {"SC_UCHAR_MAX", _SC_UCHAR_MAX
},
7910 {"SC_UINT_MAX", _SC_UINT_MAX
},
7912 #ifdef _SC_UIO_MAXIOV
7913 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV
},
7915 #ifdef _SC_ULONG_MAX
7916 {"SC_ULONG_MAX", _SC_ULONG_MAX
},
7918 #ifdef _SC_USHRT_MAX
7919 {"SC_USHRT_MAX", _SC_USHRT_MAX
},
7922 {"SC_VERSION", _SC_VERSION
},
7925 {"SC_WORD_BIT", _SC_WORD_BIT
},
7927 #ifdef _SC_XBS5_ILP32_OFF32
7928 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32
},
7930 #ifdef _SC_XBS5_ILP32_OFFBIG
7931 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG
},
7933 #ifdef _SC_XBS5_LP64_OFF64
7934 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64
},
7936 #ifdef _SC_XBS5_LPBIG_OFFBIG
7937 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG
},
7939 #ifdef _SC_XOPEN_CRYPT
7940 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT
},
7942 #ifdef _SC_XOPEN_ENH_I18N
7943 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N
},
7945 #ifdef _SC_XOPEN_LEGACY
7946 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY
},
7948 #ifdef _SC_XOPEN_REALTIME
7949 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME
},
7951 #ifdef _SC_XOPEN_REALTIME_THREADS
7952 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS
},
7954 #ifdef _SC_XOPEN_SHM
7955 {"SC_XOPEN_SHM", _SC_XOPEN_SHM
},
7957 #ifdef _SC_XOPEN_UNIX
7958 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX
},
7960 #ifdef _SC_XOPEN_VERSION
7961 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION
},
7963 #ifdef _SC_XOPEN_XCU_VERSION
7964 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION
},
7966 #ifdef _SC_XOPEN_XPG2
7967 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2
},
7969 #ifdef _SC_XOPEN_XPG3
7970 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3
},
7972 #ifdef _SC_XOPEN_XPG4
7973 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4
},
7978 conv_sysconf_confname(PyObject
*arg
, int *valuep
)
7980 return conv_confname(arg
, valuep
, posix_constants_sysconf
,
7981 sizeof(posix_constants_sysconf
)
7982 / sizeof(struct constdef
));
7985 PyDoc_STRVAR(posix_sysconf__doc__
,
7986 "sysconf(name) -> integer\n\n\
7987 Return an integer-valued system configuration variable.");
7990 posix_sysconf(PyObject
*self
, PyObject
*args
)
7992 PyObject
*result
= NULL
;
7995 if (PyArg_ParseTuple(args
, "O&:sysconf", conv_sysconf_confname
, &name
)) {
7999 value
= sysconf(name
);
8000 if (value
== -1 && errno
!= 0)
8003 result
= PyInt_FromLong(value
);
8010 /* This code is used to ensure that the tables of configuration value names
8011 * are in sorted order as required by conv_confname(), and also to build the
8012 * the exported dictionaries that are used to publish information about the
8013 * names available on the host platform.
8015 * Sorting the table at runtime ensures that the table is properly ordered
8016 * when used, even for platforms we're not able to test on. It also makes
8017 * it easier to add additional entries to the tables.
8021 cmp_constdefs(const void *v1
, const void *v2
)
8023 const struct constdef
*c1
=
8024 (const struct constdef
*) v1
;
8025 const struct constdef
*c2
=
8026 (const struct constdef
*) v2
;
8028 return strcmp(c1
->name
, c2
->name
);
8032 setup_confname_table(struct constdef
*table
, size_t tablesize
,
8033 char *tablename
, PyObject
*module
)
8038 qsort(table
, tablesize
, sizeof(struct constdef
), cmp_constdefs
);
8043 for (i
=0; i
< tablesize
; ++i
) {
8044 PyObject
*o
= PyInt_FromLong(table
[i
].value
);
8045 if (o
== NULL
|| PyDict_SetItemString(d
, table
[i
].name
, o
) == -1) {
8052 return PyModule_AddObject(module
, tablename
, d
);
8055 /* Return -1 on failure, 0 on success. */
8057 setup_confname_tables(PyObject
*module
)
8059 #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
8060 if (setup_confname_table(posix_constants_pathconf
,
8061 sizeof(posix_constants_pathconf
)
8062 / sizeof(struct constdef
),
8063 "pathconf_names", module
))
8067 if (setup_confname_table(posix_constants_confstr
,
8068 sizeof(posix_constants_confstr
)
8069 / sizeof(struct constdef
),
8070 "confstr_names", module
))
8074 if (setup_confname_table(posix_constants_sysconf
,
8075 sizeof(posix_constants_sysconf
)
8076 / sizeof(struct constdef
),
8077 "sysconf_names", module
))
8084 PyDoc_STRVAR(posix_abort__doc__
,
8085 "abort() -> does not return!\n\n\
8086 Abort the interpreter immediately. This 'dumps core' or otherwise fails\n\
8087 in the hardest way possible on the hosting operating system.");
8090 posix_abort(PyObject
*self
, PyObject
*noargs
)
8094 Py_FatalError("abort() called from Python code didn't abort!");
8099 PyDoc_STRVAR(win32_startfile__doc__
,
8100 "startfile(filepath [, operation]) - Start a file with its associated\n\
8103 When \"operation\" is not specified or \"open\", this acts like\n\
8104 double-clicking the file in Explorer, or giving the file name as an\n\
8105 argument to the DOS \"start\" command: the file is opened with whatever\n\
8106 application (if any) its extension is associated.\n\
8107 When another \"operation\" is given, it specifies what should be done with\n\
8108 the file. A typical operation is \"print\".\n\
8110 startfile returns as soon as the associated application is launched.\n\
8111 There is no option to wait for the application to close, and no way\n\
8112 to retrieve the application's exit status.\n\
8114 The filepath is relative to the current directory. If you want to use\n\
8115 an absolute path, make sure the first character is not a slash (\"/\");\n\
8116 the underlying Win32 ShellExecute function doesn't work if it is.");
8119 win32_startfile(PyObject
*self
, PyObject
*args
)
8122 char *operation
= NULL
;
8124 #ifdef Py_WIN_WIDE_FILENAMES
8125 if (unicode_file_names()) {
8126 PyObject
*unipath
, *woperation
= NULL
;
8127 if (!PyArg_ParseTuple(args
, "U|s:startfile",
8128 &unipath
, &operation
)) {
8135 woperation
= PyUnicode_DecodeASCII(operation
,
8136 strlen(operation
), NULL
);
8144 Py_BEGIN_ALLOW_THREADS
8145 rc
= ShellExecuteW((HWND
)0, woperation
? PyUnicode_AS_UNICODE(woperation
) : 0,
8146 PyUnicode_AS_UNICODE(unipath
),
8147 NULL
, NULL
, SW_SHOWNORMAL
);
8148 Py_END_ALLOW_THREADS
8150 Py_XDECREF(woperation
);
8151 if (rc
<= (HINSTANCE
)32) {
8152 PyObject
*errval
= win32_error_unicode("startfile",
8153 PyUnicode_AS_UNICODE(unipath
));
8162 if (!PyArg_ParseTuple(args
, "et|s:startfile",
8163 Py_FileSystemDefaultEncoding
, &filepath
,
8166 Py_BEGIN_ALLOW_THREADS
8167 rc
= ShellExecute((HWND
)0, operation
, filepath
,
8168 NULL
, NULL
, SW_SHOWNORMAL
);
8169 Py_END_ALLOW_THREADS
8170 if (rc
<= (HINSTANCE
)32) {
8171 PyObject
*errval
= win32_error("startfile", filepath
);
8172 PyMem_Free(filepath
);
8175 PyMem_Free(filepath
);
8181 #ifdef HAVE_GETLOADAVG
8182 PyDoc_STRVAR(posix_getloadavg__doc__
,
8183 "getloadavg() -> (float, float, float)\n\n\
8184 Return the number of processes in the system run queue averaged over\n\
8185 the last 1, 5, and 15 minutes or raises OSError if the load average\n\
8189 posix_getloadavg(PyObject
*self
, PyObject
*noargs
)
8192 if (getloadavg(loadavg
, 3)!=3) {
8193 PyErr_SetString(PyExc_OSError
, "Load averages are unobtainable");
8196 return Py_BuildValue("ddd", loadavg
[0], loadavg
[1], loadavg
[2]);
8202 PyDoc_STRVAR(win32_urandom__doc__
,
8203 "urandom(n) -> str\n\n\
8204 Return a string of n random bytes suitable for cryptographic use.");
8206 typedef BOOL (WINAPI
*CRYPTACQUIRECONTEXTA
)(HCRYPTPROV
*phProv
,\
8207 LPCSTR pszContainer
, LPCSTR pszProvider
, DWORD dwProvType
,\
8209 typedef BOOL (WINAPI
*CRYPTGENRANDOM
)(HCRYPTPROV hProv
, DWORD dwLen
,\
8212 static CRYPTGENRANDOM pCryptGenRandom
= NULL
;
8213 /* This handle is never explicitly released. Instead, the operating
8214 system will release it when the process terminates. */
8215 static HCRYPTPROV hCryptProv
= 0;
8218 win32_urandom(PyObject
*self
, PyObject
*args
)
8223 /* Read arguments */
8224 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8227 return PyErr_Format(PyExc_ValueError
,
8228 "negative argument not allowed");
8230 if (hCryptProv
== 0) {
8231 HINSTANCE hAdvAPI32
= NULL
;
8232 CRYPTACQUIRECONTEXTA pCryptAcquireContext
= NULL
;
8234 /* Obtain handle to the DLL containing CryptoAPI
8235 This should not fail */
8236 hAdvAPI32
= GetModuleHandle("advapi32.dll");
8237 if(hAdvAPI32
== NULL
)
8238 return win32_error("GetModuleHandle", NULL
);
8240 /* Obtain pointers to the CryptoAPI functions
8241 This will fail on some early versions of Win95 */
8242 pCryptAcquireContext
= (CRYPTACQUIRECONTEXTA
)GetProcAddress(
8244 "CryptAcquireContextA");
8245 if (pCryptAcquireContext
== NULL
)
8246 return PyErr_Format(PyExc_NotImplementedError
,
8247 "CryptAcquireContextA not found");
8249 pCryptGenRandom
= (CRYPTGENRANDOM
)GetProcAddress(
8250 hAdvAPI32
, "CryptGenRandom");
8251 if (pCryptGenRandom
== NULL
)
8252 return PyErr_Format(PyExc_NotImplementedError
,
8253 "CryptGenRandom not found");
8255 /* Acquire context */
8256 if (! pCryptAcquireContext(&hCryptProv
, NULL
, NULL
,
8257 PROV_RSA_FULL
, CRYPT_VERIFYCONTEXT
))
8258 return win32_error("CryptAcquireContext", NULL
);
8261 /* Allocate bytes */
8262 result
= PyString_FromStringAndSize(NULL
, howMany
);
8263 if (result
!= NULL
) {
8264 /* Get random data */
8265 memset(PyString_AS_STRING(result
), 0, howMany
); /* zero seed */
8266 if (! pCryptGenRandom(hCryptProv
, howMany
, (unsigned char*)
8267 PyString_AS_STRING(result
))) {
8269 return win32_error("CryptGenRandom", NULL
);
8277 /* Use openssl random routine */
8278 #include <openssl/rand.h>
8279 PyDoc_STRVAR(vms_urandom__doc__
,
8280 "urandom(n) -> str\n\n\
8281 Return a string of n random bytes suitable for cryptographic use.");
8284 vms_urandom(PyObject
*self
, PyObject
*args
)
8289 /* Read arguments */
8290 if (! PyArg_ParseTuple(args
, "i:urandom", &howMany
))
8293 return PyErr_Format(PyExc_ValueError
,
8294 "negative argument not allowed");
8296 /* Allocate bytes */
8297 result
= PyString_FromStringAndSize(NULL
, howMany
);
8298 if (result
!= NULL
) {
8299 /* Get random data */
8300 if (RAND_pseudo_bytes((unsigned char*)
8301 PyString_AS_STRING(result
),
8304 return PyErr_Format(PyExc_ValueError
,
8305 "RAND_pseudo_bytes");
8312 static PyMethodDef posix_methods
[] = {
8313 {"access", posix_access
, METH_VARARGS
, posix_access__doc__
},
8315 {"ttyname", posix_ttyname
, METH_VARARGS
, posix_ttyname__doc__
},
8317 {"chdir", posix_chdir
, METH_VARARGS
, posix_chdir__doc__
},
8319 {"chflags", posix_chflags
, METH_VARARGS
, posix_chflags__doc__
},
8320 #endif /* HAVE_CHFLAGS */
8321 {"chmod", posix_chmod
, METH_VARARGS
, posix_chmod__doc__
},
8323 {"fchmod", posix_fchmod
, METH_VARARGS
, posix_fchmod__doc__
},
8324 #endif /* HAVE_FCHMOD */
8326 {"chown", posix_chown
, METH_VARARGS
, posix_chown__doc__
},
8327 #endif /* HAVE_CHOWN */
8329 {"lchmod", posix_lchmod
, METH_VARARGS
, posix_lchmod__doc__
},
8330 #endif /* HAVE_LCHMOD */
8332 {"fchown", posix_fchown
, METH_VARARGS
, posix_fchown__doc__
},
8333 #endif /* HAVE_FCHOWN */
8334 #ifdef HAVE_LCHFLAGS
8335 {"lchflags", posix_lchflags
, METH_VARARGS
, posix_lchflags__doc__
},
8336 #endif /* HAVE_LCHFLAGS */
8338 {"lchown", posix_lchown
, METH_VARARGS
, posix_lchown__doc__
},
8339 #endif /* HAVE_LCHOWN */
8341 {"chroot", posix_chroot
, METH_VARARGS
, posix_chroot__doc__
},
8344 {"ctermid", posix_ctermid
, METH_NOARGS
, posix_ctermid__doc__
},
8347 {"getcwd", posix_getcwd
, METH_NOARGS
, posix_getcwd__doc__
},
8348 #ifdef Py_USING_UNICODE
8349 {"getcwdu", posix_getcwdu
, METH_NOARGS
, posix_getcwdu__doc__
},
8353 {"link", posix_link
, METH_VARARGS
, posix_link__doc__
},
8354 #endif /* HAVE_LINK */
8355 {"listdir", posix_listdir
, METH_VARARGS
, posix_listdir__doc__
},
8356 {"lstat", posix_lstat
, METH_VARARGS
, posix_lstat__doc__
},
8357 {"mkdir", posix_mkdir
, METH_VARARGS
, posix_mkdir__doc__
},
8359 {"nice", posix_nice
, METH_VARARGS
, posix_nice__doc__
},
8360 #endif /* HAVE_NICE */
8361 #ifdef HAVE_READLINK
8362 {"readlink", posix_readlink
, METH_VARARGS
, posix_readlink__doc__
},
8363 #endif /* HAVE_READLINK */
8364 {"rename", posix_rename
, METH_VARARGS
, posix_rename__doc__
},
8365 {"rmdir", posix_rmdir
, METH_VARARGS
, posix_rmdir__doc__
},
8366 {"stat", posix_stat
, METH_VARARGS
, posix_stat__doc__
},
8367 {"stat_float_times", stat_float_times
, METH_VARARGS
, stat_float_times__doc__
},
8369 {"symlink", posix_symlink
, METH_VARARGS
, posix_symlink__doc__
},
8370 #endif /* HAVE_SYMLINK */
8372 {"system", posix_system
, METH_VARARGS
, posix_system__doc__
},
8374 {"umask", posix_umask
, METH_VARARGS
, posix_umask__doc__
},
8376 {"uname", posix_uname
, METH_NOARGS
, posix_uname__doc__
},
8377 #endif /* HAVE_UNAME */
8378 {"unlink", posix_unlink
, METH_VARARGS
, posix_unlink__doc__
},
8379 {"remove", posix_unlink
, METH_VARARGS
, posix_remove__doc__
},
8380 {"utime", posix_utime
, METH_VARARGS
, posix_utime__doc__
},
8382 {"times", posix_times
, METH_NOARGS
, posix_times__doc__
},
8383 #endif /* HAVE_TIMES */
8384 {"_exit", posix__exit
, METH_VARARGS
, posix__exit__doc__
},
8386 {"execv", posix_execv
, METH_VARARGS
, posix_execv__doc__
},
8387 {"execve", posix_execve
, METH_VARARGS
, posix_execve__doc__
},
8388 #endif /* HAVE_EXECV */
8390 {"spawnv", posix_spawnv
, METH_VARARGS
, posix_spawnv__doc__
},
8391 {"spawnve", posix_spawnve
, METH_VARARGS
, posix_spawnve__doc__
},
8392 #if defined(PYOS_OS2)
8393 {"spawnvp", posix_spawnvp
, METH_VARARGS
, posix_spawnvp__doc__
},
8394 {"spawnvpe", posix_spawnvpe
, METH_VARARGS
, posix_spawnvpe__doc__
},
8395 #endif /* PYOS_OS2 */
8396 #endif /* HAVE_SPAWNV */
8398 {"fork1", posix_fork1
, METH_NOARGS
, posix_fork1__doc__
},
8399 #endif /* HAVE_FORK1 */
8401 {"fork", posix_fork
, METH_NOARGS
, posix_fork__doc__
},
8402 #endif /* HAVE_FORK */
8403 #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
8404 {"openpty", posix_openpty
, METH_NOARGS
, posix_openpty__doc__
},
8405 #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */
8407 {"forkpty", posix_forkpty
, METH_NOARGS
, posix_forkpty__doc__
},
8408 #endif /* HAVE_FORKPTY */
8410 {"getegid", posix_getegid
, METH_NOARGS
, posix_getegid__doc__
},
8411 #endif /* HAVE_GETEGID */
8413 {"geteuid", posix_geteuid
, METH_NOARGS
, posix_geteuid__doc__
},
8414 #endif /* HAVE_GETEUID */
8416 {"getgid", posix_getgid
, METH_NOARGS
, posix_getgid__doc__
},
8417 #endif /* HAVE_GETGID */
8418 #ifdef HAVE_GETGROUPS
8419 {"getgroups", posix_getgroups
, METH_NOARGS
, posix_getgroups__doc__
},
8421 {"getpid", posix_getpid
, METH_NOARGS
, posix_getpid__doc__
},
8423 {"getpgrp", posix_getpgrp
, METH_NOARGS
, posix_getpgrp__doc__
},
8424 #endif /* HAVE_GETPGRP */
8426 {"getppid", posix_getppid
, METH_NOARGS
, posix_getppid__doc__
},
8427 #endif /* HAVE_GETPPID */
8429 {"getuid", posix_getuid
, METH_NOARGS
, posix_getuid__doc__
},
8430 #endif /* HAVE_GETUID */
8431 #ifdef HAVE_GETLOGIN
8432 {"getlogin", posix_getlogin
, METH_NOARGS
, posix_getlogin__doc__
},
8435 {"kill", posix_kill
, METH_VARARGS
, posix_kill__doc__
},
8436 #endif /* HAVE_KILL */
8438 {"killpg", posix_killpg
, METH_VARARGS
, posix_killpg__doc__
},
8439 #endif /* HAVE_KILLPG */
8441 {"plock", posix_plock
, METH_VARARGS
, posix_plock__doc__
},
8442 #endif /* HAVE_PLOCK */
8444 {"popen", posix_popen
, METH_VARARGS
, posix_popen__doc__
},
8446 {"popen2", win32_popen2
, METH_VARARGS
},
8447 {"popen3", win32_popen3
, METH_VARARGS
},
8448 {"popen4", win32_popen4
, METH_VARARGS
},
8449 {"startfile", win32_startfile
, METH_VARARGS
, win32_startfile__doc__
},
8451 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8452 {"popen2", os2emx_popen2
, METH_VARARGS
},
8453 {"popen3", os2emx_popen3
, METH_VARARGS
},
8454 {"popen4", os2emx_popen4
, METH_VARARGS
},
8457 #endif /* HAVE_POPEN */
8459 {"setuid", posix_setuid
, METH_VARARGS
, posix_setuid__doc__
},
8460 #endif /* HAVE_SETUID */
8462 {"seteuid", posix_seteuid
, METH_VARARGS
, posix_seteuid__doc__
},
8463 #endif /* HAVE_SETEUID */
8465 {"setegid", posix_setegid
, METH_VARARGS
, posix_setegid__doc__
},
8466 #endif /* HAVE_SETEGID */
8467 #ifdef HAVE_SETREUID
8468 {"setreuid", posix_setreuid
, METH_VARARGS
, posix_setreuid__doc__
},
8469 #endif /* HAVE_SETREUID */
8470 #ifdef HAVE_SETREGID
8471 {"setregid", posix_setregid
, METH_VARARGS
, posix_setregid__doc__
},
8472 #endif /* HAVE_SETREGID */
8474 {"setgid", posix_setgid
, METH_VARARGS
, posix_setgid__doc__
},
8475 #endif /* HAVE_SETGID */
8476 #ifdef HAVE_SETGROUPS
8477 {"setgroups", posix_setgroups
, METH_O
, posix_setgroups__doc__
},
8478 #endif /* HAVE_SETGROUPS */
8480 {"getpgid", posix_getpgid
, METH_VARARGS
, posix_getpgid__doc__
},
8481 #endif /* HAVE_GETPGID */
8483 {"setpgrp", posix_setpgrp
, METH_NOARGS
, posix_setpgrp__doc__
},
8484 #endif /* HAVE_SETPGRP */
8486 {"wait", posix_wait
, METH_NOARGS
, posix_wait__doc__
},
8487 #endif /* HAVE_WAIT */
8489 {"wait3", posix_wait3
, METH_VARARGS
, posix_wait3__doc__
},
8490 #endif /* HAVE_WAIT3 */
8492 {"wait4", posix_wait4
, METH_VARARGS
, posix_wait4__doc__
},
8493 #endif /* HAVE_WAIT4 */
8494 #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT)
8495 {"waitpid", posix_waitpid
, METH_VARARGS
, posix_waitpid__doc__
},
8496 #endif /* HAVE_WAITPID */
8498 {"getsid", posix_getsid
, METH_VARARGS
, posix_getsid__doc__
},
8499 #endif /* HAVE_GETSID */
8501 {"setsid", posix_setsid
, METH_NOARGS
, posix_setsid__doc__
},
8502 #endif /* HAVE_SETSID */
8504 {"setpgid", posix_setpgid
, METH_VARARGS
, posix_setpgid__doc__
},
8505 #endif /* HAVE_SETPGID */
8506 #ifdef HAVE_TCGETPGRP
8507 {"tcgetpgrp", posix_tcgetpgrp
, METH_VARARGS
, posix_tcgetpgrp__doc__
},
8508 #endif /* HAVE_TCGETPGRP */
8509 #ifdef HAVE_TCSETPGRP
8510 {"tcsetpgrp", posix_tcsetpgrp
, METH_VARARGS
, posix_tcsetpgrp__doc__
},
8511 #endif /* HAVE_TCSETPGRP */
8512 {"open", posix_open
, METH_VARARGS
, posix_open__doc__
},
8513 {"close", posix_close
, METH_VARARGS
, posix_close__doc__
},
8514 {"closerange", posix_closerange
, METH_VARARGS
, posix_closerange__doc__
},
8515 {"dup", posix_dup
, METH_VARARGS
, posix_dup__doc__
},
8516 {"dup2", posix_dup2
, METH_VARARGS
, posix_dup2__doc__
},
8517 {"lseek", posix_lseek
, METH_VARARGS
, posix_lseek__doc__
},
8518 {"read", posix_read
, METH_VARARGS
, posix_read__doc__
},
8519 {"write", posix_write
, METH_VARARGS
, posix_write__doc__
},
8520 {"fstat", posix_fstat
, METH_VARARGS
, posix_fstat__doc__
},
8521 {"fdopen", posix_fdopen
, METH_VARARGS
, posix_fdopen__doc__
},
8522 {"isatty", posix_isatty
, METH_VARARGS
, posix_isatty__doc__
},
8524 {"pipe", posix_pipe
, METH_NOARGS
, posix_pipe__doc__
},
8527 {"mkfifo", posix_mkfifo
, METH_VARARGS
, posix_mkfifo__doc__
},
8529 #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
8530 {"mknod", posix_mknod
, METH_VARARGS
, posix_mknod__doc__
},
8532 #ifdef HAVE_DEVICE_MACROS
8533 {"major", posix_major
, METH_VARARGS
, posix_major__doc__
},
8534 {"minor", posix_minor
, METH_VARARGS
, posix_minor__doc__
},
8535 {"makedev", posix_makedev
, METH_VARARGS
, posix_makedev__doc__
},
8537 #ifdef HAVE_FTRUNCATE
8538 {"ftruncate", posix_ftruncate
, METH_VARARGS
, posix_ftruncate__doc__
},
8541 {"putenv", posix_putenv
, METH_VARARGS
, posix_putenv__doc__
},
8543 #ifdef HAVE_UNSETENV
8544 {"unsetenv", posix_unsetenv
, METH_VARARGS
, posix_unsetenv__doc__
},
8546 {"strerror", posix_strerror
, METH_VARARGS
, posix_strerror__doc__
},
8548 {"fchdir", posix_fchdir
, METH_O
, posix_fchdir__doc__
},
8551 {"fsync", posix_fsync
, METH_O
, posix_fsync__doc__
},
8553 #ifdef HAVE_FDATASYNC
8554 {"fdatasync", posix_fdatasync
, METH_O
, posix_fdatasync__doc__
},
8556 #ifdef HAVE_SYS_WAIT_H
8558 {"WCOREDUMP", posix_WCOREDUMP
, METH_VARARGS
, posix_WCOREDUMP__doc__
},
8559 #endif /* WCOREDUMP */
8561 {"WIFCONTINUED",posix_WIFCONTINUED
, METH_VARARGS
, posix_WIFCONTINUED__doc__
},
8562 #endif /* WIFCONTINUED */
8564 {"WIFSTOPPED", posix_WIFSTOPPED
, METH_VARARGS
, posix_WIFSTOPPED__doc__
},
8565 #endif /* WIFSTOPPED */
8567 {"WIFSIGNALED", posix_WIFSIGNALED
, METH_VARARGS
, posix_WIFSIGNALED__doc__
},
8568 #endif /* WIFSIGNALED */
8570 {"WIFEXITED", posix_WIFEXITED
, METH_VARARGS
, posix_WIFEXITED__doc__
},
8571 #endif /* WIFEXITED */
8573 {"WEXITSTATUS", posix_WEXITSTATUS
, METH_VARARGS
, posix_WEXITSTATUS__doc__
},
8574 #endif /* WEXITSTATUS */
8576 {"WTERMSIG", posix_WTERMSIG
, METH_VARARGS
, posix_WTERMSIG__doc__
},
8577 #endif /* WTERMSIG */
8579 {"WSTOPSIG", posix_WSTOPSIG
, METH_VARARGS
, posix_WSTOPSIG__doc__
},
8580 #endif /* WSTOPSIG */
8581 #endif /* HAVE_SYS_WAIT_H */
8582 #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
8583 {"fstatvfs", posix_fstatvfs
, METH_VARARGS
, posix_fstatvfs__doc__
},
8585 #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
8586 {"statvfs", posix_statvfs
, METH_VARARGS
, posix_statvfs__doc__
},
8589 {"tmpfile", posix_tmpfile
, METH_NOARGS
, posix_tmpfile__doc__
},
8592 {"tempnam", posix_tempnam
, METH_VARARGS
, posix_tempnam__doc__
},
8595 {"tmpnam", posix_tmpnam
, METH_NOARGS
, posix_tmpnam__doc__
},
8598 {"confstr", posix_confstr
, METH_VARARGS
, posix_confstr__doc__
},
8601 {"sysconf", posix_sysconf
, METH_VARARGS
, posix_sysconf__doc__
},
8603 #ifdef HAVE_FPATHCONF
8604 {"fpathconf", posix_fpathconf
, METH_VARARGS
, posix_fpathconf__doc__
},
8606 #ifdef HAVE_PATHCONF
8607 {"pathconf", posix_pathconf
, METH_VARARGS
, posix_pathconf__doc__
},
8609 {"abort", posix_abort
, METH_NOARGS
, posix_abort__doc__
},
8611 {"_getfullpathname", posix__getfullpathname
, METH_VARARGS
, NULL
},
8613 #ifdef HAVE_GETLOADAVG
8614 {"getloadavg", posix_getloadavg
, METH_NOARGS
, posix_getloadavg__doc__
},
8617 {"urandom", win32_urandom
, METH_VARARGS
, win32_urandom__doc__
},
8620 {"urandom", vms_urandom
, METH_VARARGS
, vms_urandom__doc__
},
8622 {NULL
, NULL
} /* Sentinel */
8627 ins(PyObject
*module
, char *symbol
, long value
)
8629 return PyModule_AddIntConstant(module
, symbol
, value
);
8632 #if defined(PYOS_OS2)
8633 /* Insert Platform-Specific Constant Values (Strings & Numbers) of Common Use */
8634 static int insertvalues(PyObject
*module
)
8637 ULONG values
[QSV_MAX
+1];
8641 Py_BEGIN_ALLOW_THREADS
8642 rc
= DosQuerySysInfo(1L, QSV_MAX
, &values
[1], sizeof(ULONG
) * QSV_MAX
);
8643 Py_END_ALLOW_THREADS
8645 if (rc
!= NO_ERROR
) {
8650 if (ins(module
, "meminstalled", values
[QSV_TOTPHYSMEM
])) return -1;
8651 if (ins(module
, "memkernel", values
[QSV_TOTRESMEM
])) return -1;
8652 if (ins(module
, "memvirtual", values
[QSV_TOTAVAILMEM
])) return -1;
8653 if (ins(module
, "maxpathlen", values
[QSV_MAX_PATH_LENGTH
])) return -1;
8654 if (ins(module
, "maxnamelen", values
[QSV_MAX_COMP_LENGTH
])) return -1;
8655 if (ins(module
, "revision", values
[QSV_VERSION_REVISION
])) return -1;
8656 if (ins(module
, "timeslice", values
[QSV_MIN_SLICE
])) return -1;
8658 switch (values
[QSV_VERSION_MINOR
]) {
8659 case 0: ver
= "2.00"; break;
8660 case 10: ver
= "2.10"; break;
8661 case 11: ver
= "2.11"; break;
8662 case 30: ver
= "3.00"; break;
8663 case 40: ver
= "4.00"; break;
8664 case 50: ver
= "5.00"; break;
8666 PyOS_snprintf(tmp
, sizeof(tmp
),
8667 "%d-%d", values
[QSV_VERSION_MAJOR
],
8668 values
[QSV_VERSION_MINOR
]);
8672 /* Add Indicator of the Version of the Operating System */
8673 if (PyModule_AddStringConstant(module
, "version", tmp
) < 0)
8676 /* Add Indicator of Which Drive was Used to Boot the System */
8677 tmp
[0] = 'A' + values
[QSV_BOOT_DRIVE
] - 1;
8681 return PyModule_AddStringConstant(module
, "bootdrive", tmp
);
8686 all_ins(PyObject
*d
)
8689 if (ins(d
, "F_OK", (long)F_OK
)) return -1;
8692 if (ins(d
, "R_OK", (long)R_OK
)) return -1;
8695 if (ins(d
, "W_OK", (long)W_OK
)) return -1;
8698 if (ins(d
, "X_OK", (long)X_OK
)) return -1;
8701 if (ins(d
, "NGROUPS_MAX", (long)NGROUPS_MAX
)) return -1;
8704 if (ins(d
, "TMP_MAX", (long)TMP_MAX
)) return -1;
8707 if (ins(d
, "WCONTINUED", (long)WCONTINUED
)) return -1;
8710 if (ins(d
, "WNOHANG", (long)WNOHANG
)) return -1;
8713 if (ins(d
, "WUNTRACED", (long)WUNTRACED
)) return -1;
8716 if (ins(d
, "O_RDONLY", (long)O_RDONLY
)) return -1;
8719 if (ins(d
, "O_WRONLY", (long)O_WRONLY
)) return -1;
8722 if (ins(d
, "O_RDWR", (long)O_RDWR
)) return -1;
8725 if (ins(d
, "O_NDELAY", (long)O_NDELAY
)) return -1;
8728 if (ins(d
, "O_NONBLOCK", (long)O_NONBLOCK
)) return -1;
8731 if (ins(d
, "O_APPEND", (long)O_APPEND
)) return -1;
8734 if (ins(d
, "O_DSYNC", (long)O_DSYNC
)) return -1;
8737 if (ins(d
, "O_RSYNC", (long)O_RSYNC
)) return -1;
8740 if (ins(d
, "O_SYNC", (long)O_SYNC
)) return -1;
8743 if (ins(d
, "O_NOCTTY", (long)O_NOCTTY
)) return -1;
8746 if (ins(d
, "O_CREAT", (long)O_CREAT
)) return -1;
8749 if (ins(d
, "O_EXCL", (long)O_EXCL
)) return -1;
8752 if (ins(d
, "O_TRUNC", (long)O_TRUNC
)) return -1;
8755 if (ins(d
, "O_BINARY", (long)O_BINARY
)) return -1;
8758 if (ins(d
, "O_TEXT", (long)O_TEXT
)) return -1;
8761 if (ins(d
, "O_LARGEFILE", (long)O_LARGEFILE
)) return -1;
8764 if (ins(d
, "O_SHLOCK", (long)O_SHLOCK
)) return -1;
8767 if (ins(d
, "O_EXLOCK", (long)O_EXLOCK
)) return -1;
8772 /* Don't inherit in child processes. */
8773 if (ins(d
, "O_NOINHERIT", (long)O_NOINHERIT
)) return -1;
8775 #ifdef _O_SHORT_LIVED
8776 /* Optimize for short life (keep in memory). */
8777 /* MS forgot to define this one with a non-underscore form too. */
8778 if (ins(d
, "O_SHORT_LIVED", (long)_O_SHORT_LIVED
)) return -1;
8781 /* Automatically delete when last handle is closed. */
8782 if (ins(d
, "O_TEMPORARY", (long)O_TEMPORARY
)) return -1;
8785 /* Optimize for random access. */
8786 if (ins(d
, "O_RANDOM", (long)O_RANDOM
)) return -1;
8789 /* Optimize for sequential access. */
8790 if (ins(d
, "O_SEQUENTIAL", (long)O_SEQUENTIAL
)) return -1;
8793 /* GNU extensions. */
8795 /* Send a SIGIO signal whenever input or output
8796 becomes available on file descriptor */
8797 if (ins(d
, "O_ASYNC", (long)O_ASYNC
)) return -1;
8800 /* Direct disk access. */
8801 if (ins(d
, "O_DIRECT", (long)O_DIRECT
)) return -1;
8804 /* Must be a directory. */
8805 if (ins(d
, "O_DIRECTORY", (long)O_DIRECTORY
)) return -1;
8808 /* Do not follow links. */
8809 if (ins(d
, "O_NOFOLLOW", (long)O_NOFOLLOW
)) return -1;
8812 /* Do not update the access time. */
8813 if (ins(d
, "O_NOATIME", (long)O_NOATIME
)) return -1;
8816 /* These come from sysexits.h */
8818 if (ins(d
, "EX_OK", (long)EX_OK
)) return -1;
8821 if (ins(d
, "EX_USAGE", (long)EX_USAGE
)) return -1;
8822 #endif /* EX_USAGE */
8824 if (ins(d
, "EX_DATAERR", (long)EX_DATAERR
)) return -1;
8825 #endif /* EX_DATAERR */
8827 if (ins(d
, "EX_NOINPUT", (long)EX_NOINPUT
)) return -1;
8828 #endif /* EX_NOINPUT */
8830 if (ins(d
, "EX_NOUSER", (long)EX_NOUSER
)) return -1;
8831 #endif /* EX_NOUSER */
8833 if (ins(d
, "EX_NOHOST", (long)EX_NOHOST
)) return -1;
8834 #endif /* EX_NOHOST */
8835 #ifdef EX_UNAVAILABLE
8836 if (ins(d
, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE
)) return -1;
8837 #endif /* EX_UNAVAILABLE */
8839 if (ins(d
, "EX_SOFTWARE", (long)EX_SOFTWARE
)) return -1;
8840 #endif /* EX_SOFTWARE */
8842 if (ins(d
, "EX_OSERR", (long)EX_OSERR
)) return -1;
8843 #endif /* EX_OSERR */
8845 if (ins(d
, "EX_OSFILE", (long)EX_OSFILE
)) return -1;
8846 #endif /* EX_OSFILE */
8848 if (ins(d
, "EX_CANTCREAT", (long)EX_CANTCREAT
)) return -1;
8849 #endif /* EX_CANTCREAT */
8851 if (ins(d
, "EX_IOERR", (long)EX_IOERR
)) return -1;
8852 #endif /* EX_IOERR */
8854 if (ins(d
, "EX_TEMPFAIL", (long)EX_TEMPFAIL
)) return -1;
8855 #endif /* EX_TEMPFAIL */
8857 if (ins(d
, "EX_PROTOCOL", (long)EX_PROTOCOL
)) return -1;
8858 #endif /* EX_PROTOCOL */
8860 if (ins(d
, "EX_NOPERM", (long)EX_NOPERM
)) return -1;
8861 #endif /* EX_NOPERM */
8863 if (ins(d
, "EX_CONFIG", (long)EX_CONFIG
)) return -1;
8864 #endif /* EX_CONFIG */
8866 if (ins(d
, "EX_NOTFOUND", (long)EX_NOTFOUND
)) return -1;
8867 #endif /* EX_NOTFOUND */
8870 #if defined(PYOS_OS2) && defined(PYCC_GCC)
8871 if (ins(d
, "P_WAIT", (long)P_WAIT
)) return -1;
8872 if (ins(d
, "P_NOWAIT", (long)P_NOWAIT
)) return -1;
8873 if (ins(d
, "P_OVERLAY", (long)P_OVERLAY
)) return -1;
8874 if (ins(d
, "P_DEBUG", (long)P_DEBUG
)) return -1;
8875 if (ins(d
, "P_SESSION", (long)P_SESSION
)) return -1;
8876 if (ins(d
, "P_DETACH", (long)P_DETACH
)) return -1;
8877 if (ins(d
, "P_PM", (long)P_PM
)) return -1;
8878 if (ins(d
, "P_DEFAULT", (long)P_DEFAULT
)) return -1;
8879 if (ins(d
, "P_MINIMIZE", (long)P_MINIMIZE
)) return -1;
8880 if (ins(d
, "P_MAXIMIZE", (long)P_MAXIMIZE
)) return -1;
8881 if (ins(d
, "P_FULLSCREEN", (long)P_FULLSCREEN
)) return -1;
8882 if (ins(d
, "P_WINDOWED", (long)P_WINDOWED
)) return -1;
8883 if (ins(d
, "P_FOREGROUND", (long)P_FOREGROUND
)) return -1;
8884 if (ins(d
, "P_BACKGROUND", (long)P_BACKGROUND
)) return -1;
8885 if (ins(d
, "P_NOCLOSE", (long)P_NOCLOSE
)) return -1;
8886 if (ins(d
, "P_NOSESSION", (long)P_NOSESSION
)) return -1;
8887 if (ins(d
, "P_QUOTE", (long)P_QUOTE
)) return -1;
8888 if (ins(d
, "P_TILDE", (long)P_TILDE
)) return -1;
8889 if (ins(d
, "P_UNRELATED", (long)P_UNRELATED
)) return -1;
8890 if (ins(d
, "P_DEBUGDESC", (long)P_DEBUGDESC
)) return -1;
8892 if (ins(d
, "P_WAIT", (long)_P_WAIT
)) return -1;
8893 if (ins(d
, "P_NOWAIT", (long)_P_NOWAIT
)) return -1;
8894 if (ins(d
, "P_OVERLAY", (long)_OLD_P_OVERLAY
)) return -1;
8895 if (ins(d
, "P_NOWAITO", (long)_P_NOWAITO
)) return -1;
8896 if (ins(d
, "P_DETACH", (long)_P_DETACH
)) return -1;
8900 #if defined(PYOS_OS2)
8901 if (insertvalues(d
)) return -1;
8907 #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__)
8908 #define INITFUNC initnt
8909 #define MODNAME "nt"
8911 #elif defined(PYOS_OS2)
8912 #define INITFUNC initos2
8913 #define MODNAME "os2"
8916 #define INITFUNC initposix
8917 #define MODNAME "posix"
8925 m
= Py_InitModule3(MODNAME
,
8931 /* Initialize environ dictionary */
8932 v
= convertenviron();
8934 if (v
== NULL
|| PyModule_AddObject(m
, "environ", v
) != 0)
8941 if (setup_confname_tables(m
))
8944 Py_INCREF(PyExc_OSError
);
8945 PyModule_AddObject(m
, "error", PyExc_OSError
);
8948 if (posix_putenv_garbage
== NULL
)
8949 posix_putenv_garbage
= PyDict_New();
8953 stat_result_desc
.name
= MODNAME
".stat_result";
8954 stat_result_desc
.fields
[7].name
= PyStructSequence_UnnamedField
;
8955 stat_result_desc
.fields
[8].name
= PyStructSequence_UnnamedField
;
8956 stat_result_desc
.fields
[9].name
= PyStructSequence_UnnamedField
;
8957 PyStructSequence_InitType(&StatResultType
, &stat_result_desc
);
8958 structseq_new
= StatResultType
.tp_new
;
8959 StatResultType
.tp_new
= statresult_new
;
8961 statvfs_result_desc
.name
= MODNAME
".statvfs_result";
8962 PyStructSequence_InitType(&StatVFSResultType
, &statvfs_result_desc
);
8963 #ifdef NEED_TICKS_PER_SECOND
8964 # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
8965 ticks_per_second
= sysconf(_SC_CLK_TCK
);
8967 ticks_per_second
= HZ
;
8969 ticks_per_second
= 60; /* magic fallback value; may be bogus */
8973 Py_INCREF((PyObject
*) &StatResultType
);
8974 PyModule_AddObject(m
, "stat_result", (PyObject
*) &StatResultType
);
8975 Py_INCREF((PyObject
*) &StatVFSResultType
);
8976 PyModule_AddObject(m
, "statvfs_result",
8977 (PyObject
*) &StatVFSResultType
);
8982 * Step 2 of weak-linking support on Mac OS X.
8984 * The code below removes functions that are not available on the
8985 * currently active platform.
8987 * This block allow one to use a python binary that was build on
8988 * OSX 10.4 on OSX 10.3, without loosing access to new APIs on
8991 #ifdef HAVE_FSTATVFS
8992 if (fstatvfs
== NULL
) {
8993 if (PyObject_DelAttrString(m
, "fstatvfs") == -1) {
8997 #endif /* HAVE_FSTATVFS */
9000 if (statvfs
== NULL
) {
9001 if (PyObject_DelAttrString(m
, "statvfs") == -1) {
9005 #endif /* HAVE_STATVFS */
9008 if (lchown
== NULL
) {
9009 if (PyObject_DelAttrString(m
, "lchown") == -1) {
9013 #endif /* HAVE_LCHOWN */
9016 #endif /* __APPLE__ */