Merge changes from emacs-23 branch.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* some typedefs are used in sys/file.h */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34 #include <stdlib.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #include <fcntl.h>
40
41 /* Only MS-DOS does not define `subprocesses'. */
42 #ifdef subprocesses
43
44 #include <sys/socket.h>
45 #include <netdb.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48
49 /* Are local (unix) sockets supported? */
50 #if defined (HAVE_SYS_UN_H)
51 #if !defined (AF_LOCAL) && defined (AF_UNIX)
52 #define AF_LOCAL AF_UNIX
53 #endif
54 #ifdef AF_LOCAL
55 #define HAVE_LOCAL_SOCKETS
56 #include <sys/un.h>
57 #endif
58 #endif
59
60 #if defined(HAVE_SYS_IOCTL_H)
61 #include <sys/ioctl.h>
62 #if defined(HAVE_NET_IF_H)
63 #include <net/if.h>
64 #endif /* HAVE_NET_IF_H */
65 #endif /* HAVE_SYS_IOCTL_H */
66
67 #ifdef NEED_BSDTTY
68 #include <bsdtty.h>
69 #endif
70
71 #ifdef HAVE_SYS_WAIT
72 #include <sys/wait.h>
73 #endif
74
75 #ifdef HAVE_RES_INIT
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <resolv.h>
79 #endif
80
81 #ifdef HAVE_UTIL_H
82 #include <util.h>
83 #endif
84
85 #endif /* subprocesses */
86
87 #include "lisp.h"
88 #include "systime.h"
89 #include "systty.h"
90
91 #include "window.h"
92 #include "buffer.h"
93 #include "character.h"
94 #include "coding.h"
95 #include "process.h"
96 #include "frame.h"
97 #include "termhooks.h"
98 #include "termopts.h"
99 #include "commands.h"
100 #include "keyboard.h"
101 #include "blockinput.h"
102 #include "dispextern.h"
103 #include "composite.h"
104 #include "atimer.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
107 #include "syswait.h"
108
109 #if defined (USE_GTK) || defined (HAVE_GCONF)
110 #include "xgselect.h"
111 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
112 #ifdef HAVE_NS
113 #include "nsterm.h"
114 #endif
115 extern int timers_run;
116
117 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
118 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
119 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
120 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
121 Lisp_Object QCname, QCtype;
122 \f
123 /* Non-zero if keyboard input is on hold, zero otherwise. */
124
125 static int kbd_is_on_hold;
126
127 /* Nonzero means delete a process right away if it exits. */
128 static int delete_exited_processes;
129
130 /* Nonzero means don't run process sentinels. This is used
131 when exiting. */
132 int inhibit_sentinels;
133
134 #ifdef subprocesses
135
136 Lisp_Object Qprocessp;
137 Lisp_Object Qrun, Qstop, Qsignal;
138 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
139 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
140 Lisp_Object Qreal, Qnetwork, Qserial;
141 #ifdef AF_INET6
142 Lisp_Object Qipv6;
143 #endif
144 Lisp_Object QCport, QCspeed, QCprocess;
145 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
146 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
147 Lisp_Object QCbuffer, QChost, QCservice;
148 Lisp_Object QClocal, QCremote, QCcoding;
149 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
150 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
151 Lisp_Object Qlast_nonmenu_event;
152 /* QCfamily is declared and initialized in xfaces.c,
153 QCfilter in keyboard.c. */
154 extern Lisp_Object QCfamily, QCfilter;
155
156 /* Qexit is declared and initialized in eval.c. */
157
158 /* QCfamily is defined in xfaces.c. */
159 extern Lisp_Object QCfamily;
160 /* QCfilter is defined in keyboard.c. */
161 extern Lisp_Object QCfilter;
162
163 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
164 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
165 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
166 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
167
168 /* Define first descriptor number available for subprocesses. */
169 #define FIRST_PROC_DESC 3
170
171 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
172 testing SIGCHLD. */
173
174 #if !defined (SIGCHLD) && defined (SIGCLD)
175 #define SIGCHLD SIGCLD
176 #endif /* SIGCLD */
177
178 extern const char *get_operating_system_release (void);
179
180 /* From sysdep.c or w32.c */
181 extern int serial_open (char *port);
182 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
183
184 #ifndef HAVE_H_ERRNO
185 extern int h_errno;
186 #endif
187
188 /* t means use pty, nil means use a pipe,
189 maybe other values to come. */
190 static Lisp_Object Vprocess_connection_type;
191
192 /* These next two vars are non-static since sysdep.c uses them in the
193 emulation of `select'. */
194 /* Number of events of change of status of a process. */
195 int process_tick;
196 /* Number of events for which the user or sentinel has been notified. */
197 int update_tick;
198
199 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
200
201 #ifdef BROKEN_NON_BLOCKING_CONNECT
202 #undef NON_BLOCKING_CONNECT
203 #else
204 #ifndef NON_BLOCKING_CONNECT
205 #ifdef HAVE_SELECT
206 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
207 #if defined (O_NONBLOCK) || defined (O_NDELAY)
208 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
209 #define NON_BLOCKING_CONNECT
210 #endif /* EWOULDBLOCK || EINPROGRESS */
211 #endif /* O_NONBLOCK || O_NDELAY */
212 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
213 #endif /* HAVE_SELECT */
214 #endif /* NON_BLOCKING_CONNECT */
215 #endif /* BROKEN_NON_BLOCKING_CONNECT */
216
217 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
221
222 #ifdef BROKEN_DATAGRAM_SOCKETS
223 #undef DATAGRAM_SOCKETS
224 #else
225 #ifndef DATAGRAM_SOCKETS
226 #if defined (HAVE_SELECT) || defined (FIONREAD)
227 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
228 #define DATAGRAM_SOCKETS
229 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
230 #endif /* HAVE_SELECT || FIONREAD */
231 #endif /* DATAGRAM_SOCKETS */
232 #endif /* BROKEN_DATAGRAM_SOCKETS */
233
234 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
235 # define HAVE_SEQPACKET
236 #endif
237
238 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
239 #ifdef EMACS_HAS_USECS
240 #define ADAPTIVE_READ_BUFFERING
241 #endif
242 #endif
243
244 #ifdef ADAPTIVE_READ_BUFFERING
245 #define READ_OUTPUT_DELAY_INCREMENT 10000
246 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
247 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
248
249 /* Number of processes which have a non-zero read_output_delay,
250 and therefore might be delayed for adaptive read buffering. */
251
252 static int process_output_delay_count;
253
254 /* Non-zero if any process has non-nil read_output_skip. */
255
256 static int process_output_skip;
257
258 /* Non-nil means to delay reading process output to improve buffering.
259 A value of t means that delay is reset after each send, any other
260 non-nil value does not reset the delay. A value of nil disables
261 adaptive read buffering completely. */
262 static Lisp_Object Vprocess_adaptive_read_buffering;
263 #else
264 #define process_output_delay_count 0
265 #endif
266
267 static int keyboard_bit_set (SELECT_TYPE *);
268 static void deactivate_process (Lisp_Object);
269 static void status_notify (struct Lisp_Process *);
270 static int read_process_output (Lisp_Object, int);
271 static void create_pty (Lisp_Object);
272
273 /* If we support a window system, turn on the code to poll periodically
274 to detect C-g. It isn't actually used when doing interrupt input. */
275 #ifdef HAVE_WINDOW_SYSTEM
276 #define POLL_FOR_INPUT
277 #endif
278
279 static Lisp_Object get_process (register Lisp_Object name);
280 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
281
282 /* Mask of bits indicating the descriptors that we wait for input on. */
283
284 static SELECT_TYPE input_wait_mask;
285
286 /* Mask that excludes keyboard input descriptor(s). */
287
288 static SELECT_TYPE non_keyboard_wait_mask;
289
290 /* Mask that excludes process input descriptor(s). */
291
292 static SELECT_TYPE non_process_wait_mask;
293
294 /* Mask for the gpm mouse input descriptor. */
295
296 static SELECT_TYPE gpm_wait_mask;
297
298 #ifdef NON_BLOCKING_CONNECT
299 /* Mask of bits indicating the descriptors that we wait for connect to
300 complete on. Once they complete, they are removed from this mask
301 and added to the input_wait_mask and non_keyboard_wait_mask. */
302
303 static SELECT_TYPE connect_wait_mask;
304
305 /* Number of bits set in connect_wait_mask. */
306 static int num_pending_connects;
307
308 #define IF_NON_BLOCKING_CONNECT(s) s
309 #else /* NON_BLOCKING_CONNECT */
310 #define IF_NON_BLOCKING_CONNECT(s)
311 #endif /* NON_BLOCKING_CONNECT */
312
313 /* The largest descriptor currently in use for a process object. */
314 static int max_process_desc;
315
316 /* The largest descriptor currently in use for keyboard input. */
317 static int max_keyboard_desc;
318
319 /* The largest descriptor currently in use for gpm mouse input. */
320 static int max_gpm_desc;
321
322 /* Indexed by descriptor, gives the process (if any) for that descriptor */
323 Lisp_Object chan_process[MAXDESC];
324
325 /* Alist of elements (NAME . PROCESS) */
326 Lisp_Object Vprocess_alist;
327
328 /* Buffered-ahead input char from process, indexed by channel.
329 -1 means empty (no char is buffered).
330 Used on sys V where the only way to tell if there is any
331 output from the process is to read at least one char.
332 Always -1 on systems that support FIONREAD. */
333
334 /* Don't make static; need to access externally. */
335 int proc_buffered_char[MAXDESC];
336
337 /* Table of `struct coding-system' for each process. */
338 static struct coding_system *proc_decode_coding_system[MAXDESC];
339 static struct coding_system *proc_encode_coding_system[MAXDESC];
340
341 #ifdef DATAGRAM_SOCKETS
342 /* Table of `partner address' for datagram sockets. */
343 struct sockaddr_and_len {
344 struct sockaddr *sa;
345 int len;
346 } datagram_address[MAXDESC];
347 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
348 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
349 #else
350 #define DATAGRAM_CHAN_P(chan) (0)
351 #define DATAGRAM_CONN_P(proc) (0)
352 #endif
353
354 /* Maximum number of bytes to send to a pty without an eof. */
355 static int pty_max_bytes;
356
357 #ifdef HAVE_PTYS
358 #ifdef HAVE_PTY_H
359 #include <pty.h>
360 #endif
361 /* The file name of the pty opened by allocate_pty. */
362
363 static char pty_name[24];
364 #endif
365 \f
366 /* Compute the Lisp form of the process status, p->status, from
367 the numeric status that was returned by `wait'. */
368
369 static Lisp_Object status_convert (int);
370
371 static void
372 update_status (struct Lisp_Process *p)
373 {
374 eassert (p->raw_status_new);
375 p->status = status_convert (p->raw_status);
376 p->raw_status_new = 0;
377 }
378
379 /* Convert a process status word in Unix format to
380 the list that we use internally. */
381
382 static Lisp_Object
383 status_convert (int w)
384 {
385 if (WIFSTOPPED (w))
386 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
387 else if (WIFEXITED (w))
388 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
389 WCOREDUMP (w) ? Qt : Qnil));
390 else if (WIFSIGNALED (w))
391 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
392 WCOREDUMP (w) ? Qt : Qnil));
393 else
394 return Qrun;
395 }
396
397 /* Given a status-list, extract the three pieces of information
398 and store them individually through the three pointers. */
399
400 static void
401 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
402 {
403 Lisp_Object tem;
404
405 if (SYMBOLP (l))
406 {
407 *symbol = l;
408 *code = 0;
409 *coredump = 0;
410 }
411 else
412 {
413 *symbol = XCAR (l);
414 tem = XCDR (l);
415 *code = XFASTINT (XCAR (tem));
416 tem = XCDR (tem);
417 *coredump = !NILP (tem);
418 }
419 }
420
421 /* Return a string describing a process status list. */
422
423 static Lisp_Object
424 status_message (struct Lisp_Process *p)
425 {
426 Lisp_Object status = p->status;
427 Lisp_Object symbol;
428 int code, coredump;
429 Lisp_Object string, string2;
430
431 decode_status (status, &symbol, &code, &coredump);
432
433 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
434 {
435 char *signame;
436 synchronize_system_messages_locale ();
437 signame = strsignal (code);
438 if (signame == 0)
439 string = build_string ("unknown");
440 else
441 {
442 int c1, c2;
443
444 string = make_unibyte_string (signame, strlen (signame));
445 if (! NILP (Vlocale_coding_system))
446 string = (code_convert_string_norecord
447 (string, Vlocale_coding_system, 0));
448 c1 = STRING_CHAR ((char *) SDATA (string));
449 c2 = DOWNCASE (c1);
450 if (c1 != c2)
451 Faset (string, make_number (0), make_number (c2));
452 }
453 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
454 return concat2 (string, string2);
455 }
456 else if (EQ (symbol, Qexit))
457 {
458 if (NETCONN1_P (p))
459 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
460 if (code == 0)
461 return build_string ("finished\n");
462 string = Fnumber_to_string (make_number (code));
463 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
464 return concat3 (build_string ("exited abnormally with code "),
465 string, string2);
466 }
467 else if (EQ (symbol, Qfailed))
468 {
469 string = Fnumber_to_string (make_number (code));
470 string2 = build_string ("\n");
471 return concat3 (build_string ("failed with code "),
472 string, string2);
473 }
474 else
475 return Fcopy_sequence (Fsymbol_name (symbol));
476 }
477 \f
478 #ifdef HAVE_PTYS
479
480 /* Open an available pty, returning a file descriptor.
481 Return -1 on failure.
482 The file name of the terminal corresponding to the pty
483 is left in the variable pty_name. */
484
485 static int
486 allocate_pty (void)
487 {
488 register int c, i;
489 int fd;
490
491 #ifdef PTY_ITERATION
492 PTY_ITERATION
493 #else
494 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
495 for (i = 0; i < 16; i++)
496 #endif
497 {
498 struct stat stb; /* Used in some PTY_OPEN. */
499 #ifdef PTY_NAME_SPRINTF
500 PTY_NAME_SPRINTF
501 #else
502 sprintf (pty_name, "/dev/pty%c%x", c, i);
503 #endif /* no PTY_NAME_SPRINTF */
504
505 #ifdef PTY_OPEN
506 PTY_OPEN;
507 #else /* no PTY_OPEN */
508 {
509 { /* Some systems name their pseudoterminals so that there are gaps in
510 the usual sequence - for example, on HP9000/S700 systems, there
511 are no pseudoterminals with names ending in 'f'. So we wait for
512 three failures in a row before deciding that we've reached the
513 end of the ptys. */
514 int failed_count = 0;
515
516 if (stat (pty_name, &stb) < 0)
517 {
518 failed_count++;
519 if (failed_count >= 3)
520 return -1;
521 }
522 else
523 failed_count = 0;
524 }
525 # ifdef O_NONBLOCK
526 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
527 # else
528 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
529 # endif
530 }
531 #endif /* no PTY_OPEN */
532
533 if (fd >= 0)
534 {
535 /* check to make certain that both sides are available
536 this avoids a nasty yet stupid bug in rlogins */
537 #ifdef PTY_TTY_NAME_SPRINTF
538 PTY_TTY_NAME_SPRINTF
539 #else
540 sprintf (pty_name, "/dev/tty%c%x", c, i);
541 #endif /* no PTY_TTY_NAME_SPRINTF */
542 if (access (pty_name, 6) != 0)
543 {
544 emacs_close (fd);
545 # ifndef __sgi
546 continue;
547 # else
548 return -1;
549 # endif /* __sgi */
550 }
551 setup_pty (fd);
552 return fd;
553 }
554 }
555 return -1;
556 }
557 #endif /* HAVE_PTYS */
558 \f
559 static Lisp_Object
560 make_process (Lisp_Object name)
561 {
562 register Lisp_Object val, tem, name1;
563 register struct Lisp_Process *p;
564 char suffix[10];
565 register int i;
566
567 p = allocate_process ();
568
569 p->infd = -1;
570 p->outfd = -1;
571 p->tick = 0;
572 p->update_tick = 0;
573 p->pid = 0;
574 p->pty_flag = 0;
575 p->raw_status_new = 0;
576 p->status = Qrun;
577 p->mark = Fmake_marker ();
578 p->kill_without_query = 0;
579
580 #ifdef ADAPTIVE_READ_BUFFERING
581 p->adaptive_read_buffering = 0;
582 p->read_output_delay = 0;
583 p->read_output_skip = 0;
584 #endif
585
586 /* If name is already in use, modify it until it is unused. */
587
588 name1 = name;
589 for (i = 1; ; i++)
590 {
591 tem = Fget_process (name1);
592 if (NILP (tem)) break;
593 sprintf (suffix, "<%d>", i);
594 name1 = concat2 (name, build_string (suffix));
595 }
596 name = name1;
597 p->name = name;
598 XSETPROCESS (val, p);
599 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
600 return val;
601 }
602
603 static void
604 remove_process (register Lisp_Object proc)
605 {
606 register Lisp_Object pair;
607
608 pair = Frassq (proc, Vprocess_alist);
609 Vprocess_alist = Fdelq (pair, Vprocess_alist);
610
611 deactivate_process (proc);
612 }
613
614 \f
615 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
616 doc: /* Return t if OBJECT is a process. */)
617 (Lisp_Object object)
618 {
619 return PROCESSP (object) ? Qt : Qnil;
620 }
621
622 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
623 doc: /* Return the process named NAME, or nil if there is none. */)
624 (register Lisp_Object name)
625 {
626 if (PROCESSP (name))
627 return name;
628 CHECK_STRING (name);
629 return Fcdr (Fassoc (name, Vprocess_alist));
630 }
631
632 /* This is how commands for the user decode process arguments. It
633 accepts a process, a process name, a buffer, a buffer name, or nil.
634 Buffers denote the first process in the buffer, and nil denotes the
635 current buffer. */
636
637 static Lisp_Object
638 get_process (register Lisp_Object name)
639 {
640 register Lisp_Object proc, obj;
641 if (STRINGP (name))
642 {
643 obj = Fget_process (name);
644 if (NILP (obj))
645 obj = Fget_buffer (name);
646 if (NILP (obj))
647 error ("Process %s does not exist", SDATA (name));
648 }
649 else if (NILP (name))
650 obj = Fcurrent_buffer ();
651 else
652 obj = name;
653
654 /* Now obj should be either a buffer object or a process object.
655 */
656 if (BUFFERP (obj))
657 {
658 proc = Fget_buffer_process (obj);
659 if (NILP (proc))
660 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
661 }
662 else
663 {
664 CHECK_PROCESS (obj);
665 proc = obj;
666 }
667 return proc;
668 }
669
670
671 #ifdef SIGCHLD
672 /* Fdelete_process promises to immediately forget about the process, but in
673 reality, Emacs needs to remember those processes until they have been
674 treated by sigchld_handler; otherwise this handler would consider the
675 process as being synchronous and say that the synchronous process is
676 dead. */
677 static Lisp_Object deleted_pid_list;
678 #endif
679
680 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
681 doc: /* Delete PROCESS: kill it and forget about it immediately.
682 PROCESS may be a process, a buffer, the name of a process or buffer, or
683 nil, indicating the current buffer's process. */)
684 (register Lisp_Object process)
685 {
686 register struct Lisp_Process *p;
687
688 process = get_process (process);
689 p = XPROCESS (process);
690
691 p->raw_status_new = 0;
692 if (NETCONN1_P (p) || SERIALCONN1_P (p))
693 {
694 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
695 p->tick = ++process_tick;
696 status_notify (p);
697 redisplay_preserve_echo_area (13);
698 }
699 else if (p->infd >= 0)
700 {
701 #ifdef SIGCHLD
702 Lisp_Object symbol;
703 /* Assignment to EMACS_INT stops GCC whining about limited range
704 of data type. */
705 EMACS_INT pid = p->pid;
706
707 /* No problem storing the pid here, as it is still in Vprocess_alist. */
708 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
709 /* GC treated elements set to nil. */
710 Fdelq (Qnil, deleted_pid_list));
711 /* If the process has already signaled, remove it from the list. */
712 if (p->raw_status_new)
713 update_status (p);
714 symbol = p->status;
715 if (CONSP (p->status))
716 symbol = XCAR (p->status);
717 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
718 deleted_pid_list
719 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
720 else
721 #endif
722 {
723 Fkill_process (process, Qnil);
724 /* Do this now, since remove_process will make sigchld_handler do nothing. */
725 p->status
726 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
727 p->tick = ++process_tick;
728 status_notify (p);
729 redisplay_preserve_echo_area (13);
730 }
731 }
732 remove_process (process);
733 return Qnil;
734 }
735 \f
736 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
737 doc: /* Return the status of PROCESS.
738 The returned value is one of the following symbols:
739 run -- for a process that is running.
740 stop -- for a process stopped but continuable.
741 exit -- for a process that has exited.
742 signal -- for a process that has got a fatal signal.
743 open -- for a network stream connection that is open.
744 listen -- for a network stream server that is listening.
745 closed -- for a network stream connection that is closed.
746 connect -- when waiting for a non-blocking connection to complete.
747 failed -- when a non-blocking connection has failed.
748 nil -- if arg is a process name and no such process exists.
749 PROCESS may be a process, a buffer, the name of a process, or
750 nil, indicating the current buffer's process. */)
751 (register Lisp_Object process)
752 {
753 register struct Lisp_Process *p;
754 register Lisp_Object status;
755
756 if (STRINGP (process))
757 process = Fget_process (process);
758 else
759 process = get_process (process);
760
761 if (NILP (process))
762 return process;
763
764 p = XPROCESS (process);
765 if (p->raw_status_new)
766 update_status (p);
767 status = p->status;
768 if (CONSP (status))
769 status = XCAR (status);
770 if (NETCONN1_P (p) || SERIALCONN1_P (p))
771 {
772 if (EQ (status, Qexit))
773 status = Qclosed;
774 else if (EQ (p->command, Qt))
775 status = Qstop;
776 else if (EQ (status, Qrun))
777 status = Qopen;
778 }
779 return status;
780 }
781
782 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
783 1, 1, 0,
784 doc: /* Return the exit status of PROCESS or the signal number that killed it.
785 If PROCESS has not yet exited or died, return 0. */)
786 (register Lisp_Object process)
787 {
788 CHECK_PROCESS (process);
789 if (XPROCESS (process)->raw_status_new)
790 update_status (XPROCESS (process));
791 if (CONSP (XPROCESS (process)->status))
792 return XCAR (XCDR (XPROCESS (process)->status));
793 return make_number (0);
794 }
795
796 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
797 doc: /* Return the process id of PROCESS.
798 This is the pid of the external process which PROCESS uses or talks to.
799 For a network connection, this value is nil. */)
800 (register Lisp_Object process)
801 {
802 /* Assignment to EMACS_INT stops GCC whining about limited range of
803 data type. */
804 EMACS_INT pid;
805
806 CHECK_PROCESS (process);
807 pid = XPROCESS (process)->pid;
808 return (pid ? make_fixnum_or_float (pid) : Qnil);
809 }
810
811 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
812 doc: /* Return the name of PROCESS, as a string.
813 This is the name of the program invoked in PROCESS,
814 possibly modified to make it unique among process names. */)
815 (register Lisp_Object process)
816 {
817 CHECK_PROCESS (process);
818 return XPROCESS (process)->name;
819 }
820
821 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
822 doc: /* Return the command that was executed to start PROCESS.
823 This is a list of strings, the first string being the program executed
824 and the rest of the strings being the arguments given to it.
825 For a network or serial process, this is nil (process is running) or t
826 \(process is stopped). */)
827 (register Lisp_Object process)
828 {
829 CHECK_PROCESS (process);
830 return XPROCESS (process)->command;
831 }
832
833 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
834 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
835 This is the terminal that the process itself reads and writes on,
836 not the name of the pty that Emacs uses to talk with that terminal. */)
837 (register Lisp_Object process)
838 {
839 CHECK_PROCESS (process);
840 return XPROCESS (process)->tty_name;
841 }
842
843 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
844 2, 2, 0,
845 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
846 (register Lisp_Object process, Lisp_Object buffer)
847 {
848 struct Lisp_Process *p;
849
850 CHECK_PROCESS (process);
851 if (!NILP (buffer))
852 CHECK_BUFFER (buffer);
853 p = XPROCESS (process);
854 p->buffer = buffer;
855 if (NETCONN1_P (p) || SERIALCONN1_P (p))
856 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
857 setup_process_coding_systems (process);
858 return buffer;
859 }
860
861 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
862 1, 1, 0,
863 doc: /* Return the buffer PROCESS is associated with.
864 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
865 (register Lisp_Object process)
866 {
867 CHECK_PROCESS (process);
868 return XPROCESS (process)->buffer;
869 }
870
871 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
872 1, 1, 0,
873 doc: /* Return the marker for the end of the last output from PROCESS. */)
874 (register Lisp_Object process)
875 {
876 CHECK_PROCESS (process);
877 return XPROCESS (process)->mark;
878 }
879
880 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
881 2, 2, 0,
882 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
883 A value of t means stop accepting output from the process.
884
885 When a process has a filter, its buffer is not used for output.
886 Instead, each time it does output, the entire string of output is
887 passed to the filter.
888
889 The filter gets two arguments: the process and the string of output.
890 The string argument is normally a multibyte string, except:
891 - if the process' input coding system is no-conversion or raw-text,
892 it is a unibyte string (the non-converted input), or else
893 - if `default-enable-multibyte-characters' is nil, it is a unibyte
894 string (the result of converting the decoded input multibyte
895 string to unibyte with `string-make-unibyte'). */)
896 (register Lisp_Object process, Lisp_Object filter)
897 {
898 struct Lisp_Process *p;
899
900 CHECK_PROCESS (process);
901 p = XPROCESS (process);
902
903 /* Don't signal an error if the process' input file descriptor
904 is closed. This could make debugging Lisp more difficult,
905 for example when doing something like
906
907 (setq process (start-process ...))
908 (debug)
909 (set-process-filter process ...) */
910
911 if (p->infd >= 0)
912 {
913 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
914 {
915 FD_CLR (p->infd, &input_wait_mask);
916 FD_CLR (p->infd, &non_keyboard_wait_mask);
917 }
918 else if (EQ (p->filter, Qt)
919 /* Network or serial process not stopped: */
920 && !EQ (p->command, Qt))
921 {
922 FD_SET (p->infd, &input_wait_mask);
923 FD_SET (p->infd, &non_keyboard_wait_mask);
924 }
925 }
926
927 p->filter = filter;
928 if (NETCONN1_P (p) || SERIALCONN1_P (p))
929 p->childp = Fplist_put (p->childp, QCfilter, filter);
930 setup_process_coding_systems (process);
931 return filter;
932 }
933
934 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
935 1, 1, 0,
936 doc: /* Returns the filter function of PROCESS; nil if none.
937 See `set-process-filter' for more info on filter functions. */)
938 (register Lisp_Object process)
939 {
940 CHECK_PROCESS (process);
941 return XPROCESS (process)->filter;
942 }
943
944 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
945 2, 2, 0,
946 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
947 The sentinel is called as a function when the process changes state.
948 It gets two arguments: the process, and a string describing the change. */)
949 (register Lisp_Object process, Lisp_Object sentinel)
950 {
951 struct Lisp_Process *p;
952
953 CHECK_PROCESS (process);
954 p = XPROCESS (process);
955
956 p->sentinel = sentinel;
957 if (NETCONN1_P (p) || SERIALCONN1_P (p))
958 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
959 return sentinel;
960 }
961
962 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
963 1, 1, 0,
964 doc: /* Return the sentinel of PROCESS; nil if none.
965 See `set-process-sentinel' for more info on sentinels. */)
966 (register Lisp_Object process)
967 {
968 CHECK_PROCESS (process);
969 return XPROCESS (process)->sentinel;
970 }
971
972 DEFUN ("set-process-window-size", Fset_process_window_size,
973 Sset_process_window_size, 3, 3, 0,
974 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
975 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
976 {
977 CHECK_PROCESS (process);
978 CHECK_NATNUM (height);
979 CHECK_NATNUM (width);
980
981 if (XPROCESS (process)->infd < 0
982 || set_window_size (XPROCESS (process)->infd,
983 XINT (height), XINT (width)) <= 0)
984 return Qnil;
985 else
986 return Qt;
987 }
988
989 DEFUN ("set-process-inherit-coding-system-flag",
990 Fset_process_inherit_coding_system_flag,
991 Sset_process_inherit_coding_system_flag, 2, 2, 0,
992 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
993 If the second argument FLAG is non-nil, then the variable
994 `buffer-file-coding-system' of the buffer associated with PROCESS
995 will be bound to the value of the coding system used to decode
996 the process output.
997
998 This is useful when the coding system specified for the process buffer
999 leaves either the character code conversion or the end-of-line conversion
1000 unspecified, or if the coding system used to decode the process output
1001 is more appropriate for saving the process buffer.
1002
1003 Binding the variable `inherit-process-coding-system' to non-nil before
1004 starting the process is an alternative way of setting the inherit flag
1005 for the process which will run. */)
1006 (register Lisp_Object process, Lisp_Object flag)
1007 {
1008 CHECK_PROCESS (process);
1009 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1010 return flag;
1011 }
1012
1013 DEFUN ("set-process-query-on-exit-flag",
1014 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1015 2, 2, 0,
1016 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1017 If the second argument FLAG is non-nil, Emacs will query the user before
1018 exiting or killing a buffer if PROCESS is running. */)
1019 (register Lisp_Object process, Lisp_Object flag)
1020 {
1021 CHECK_PROCESS (process);
1022 XPROCESS (process)->kill_without_query = NILP (flag);
1023 return flag;
1024 }
1025
1026 DEFUN ("process-query-on-exit-flag",
1027 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1028 1, 1, 0,
1029 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1030 (register Lisp_Object process)
1031 {
1032 CHECK_PROCESS (process);
1033 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1034 }
1035
1036 #ifdef DATAGRAM_SOCKETS
1037 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1038 #endif
1039
1040 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1041 1, 2, 0,
1042 doc: /* Return the contact info of PROCESS; t for a real child.
1043 For a network or serial connection, the value depends on the optional
1044 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1045 SERVICE) for a network connection or (PORT SPEED) for a serial
1046 connection. If KEY is t, the complete contact information for the
1047 connection is returned, else the specific value for the keyword KEY is
1048 returned. See `make-network-process' or `make-serial-process' for a
1049 list of keywords. */)
1050 (register Lisp_Object process, Lisp_Object key)
1051 {
1052 Lisp_Object contact;
1053
1054 CHECK_PROCESS (process);
1055 contact = XPROCESS (process)->childp;
1056
1057 #ifdef DATAGRAM_SOCKETS
1058 if (DATAGRAM_CONN_P (process)
1059 && (EQ (key, Qt) || EQ (key, QCremote)))
1060 contact = Fplist_put (contact, QCremote,
1061 Fprocess_datagram_address (process));
1062 #endif
1063
1064 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1065 return contact;
1066 if (NILP (key) && NETCONN_P (process))
1067 return Fcons (Fplist_get (contact, QChost),
1068 Fcons (Fplist_get (contact, QCservice), Qnil));
1069 if (NILP (key) && SERIALCONN_P (process))
1070 return Fcons (Fplist_get (contact, QCport),
1071 Fcons (Fplist_get (contact, QCspeed), Qnil));
1072 return Fplist_get (contact, key);
1073 }
1074
1075 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1076 1, 1, 0,
1077 doc: /* Return the plist of PROCESS. */)
1078 (register Lisp_Object process)
1079 {
1080 CHECK_PROCESS (process);
1081 return XPROCESS (process)->plist;
1082 }
1083
1084 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1085 2, 2, 0,
1086 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1087 (register Lisp_Object process, Lisp_Object plist)
1088 {
1089 CHECK_PROCESS (process);
1090 CHECK_LIST (plist);
1091
1092 XPROCESS (process)->plist = plist;
1093 return plist;
1094 }
1095
1096 #if 0 /* Turned off because we don't currently record this info
1097 in the process. Perhaps add it. */
1098 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1099 doc: /* Return the connection type of PROCESS.
1100 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1101 a socket connection. */)
1102 (Lisp_Object process)
1103 {
1104 return XPROCESS (process)->type;
1105 }
1106 #endif
1107
1108 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1109 doc: /* Return the connection type of PROCESS.
1110 The value is either the symbol `real', `network', or `serial'.
1111 PROCESS may be a process, a buffer, the name of a process or buffer, or
1112 nil, indicating the current buffer's process. */)
1113 (Lisp_Object process)
1114 {
1115 Lisp_Object proc;
1116 proc = get_process (process);
1117 return XPROCESS (proc)->type;
1118 }
1119
1120 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1121 1, 2, 0,
1122 doc: /* Convert network ADDRESS from internal format to a string.
1123 A 4 or 5 element vector represents an IPv4 address (with port number).
1124 An 8 or 9 element vector represents an IPv6 address (with port number).
1125 If optional second argument OMIT-PORT is non-nil, don't include a port
1126 number in the string, even when present in ADDRESS.
1127 Returns nil if format of ADDRESS is invalid. */)
1128 (Lisp_Object address, Lisp_Object omit_port)
1129 {
1130 if (NILP (address))
1131 return Qnil;
1132
1133 if (STRINGP (address)) /* AF_LOCAL */
1134 return address;
1135
1136 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1137 {
1138 register struct Lisp_Vector *p = XVECTOR (address);
1139 Lisp_Object args[10];
1140 int nargs, i;
1141
1142 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1143 {
1144 args[0] = build_string ("%d.%d.%d.%d");
1145 nargs = 4;
1146 }
1147 else if (p->size == 5)
1148 {
1149 args[0] = build_string ("%d.%d.%d.%d:%d");
1150 nargs = 5;
1151 }
1152 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1153 {
1154 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1155 nargs = 8;
1156 }
1157 else if (p->size == 9)
1158 {
1159 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1160 nargs = 9;
1161 }
1162 else
1163 return Qnil;
1164
1165 for (i = 0; i < nargs; i++)
1166 {
1167 EMACS_INT element = XINT (p->contents[i]);
1168
1169 if (element < 0 || element > 65535)
1170 return Qnil;
1171
1172 if (nargs <= 5 /* IPv4 */
1173 && i < 4 /* host, not port */
1174 && element > 255)
1175 return Qnil;
1176
1177 args[i+1] = p->contents[i];
1178 }
1179
1180 return Fformat (nargs+1, args);
1181 }
1182
1183 if (CONSP (address))
1184 {
1185 Lisp_Object args[2];
1186 args[0] = build_string ("<Family %d>");
1187 args[1] = Fcar (address);
1188 return Fformat (2, args);
1189 }
1190
1191 return Qnil;
1192 }
1193 \f
1194 static Lisp_Object
1195 list_processes_1 (Lisp_Object query_only)
1196 {
1197 register Lisp_Object tail, tem;
1198 Lisp_Object proc, minspace, tem1;
1199 register struct Lisp_Process *p;
1200 char tembuf[300];
1201 int w_proc, w_buffer, w_tty;
1202 int exited = 0;
1203 Lisp_Object i_status, i_buffer, i_tty, i_command;
1204
1205 w_proc = 4; /* Proc */
1206 w_buffer = 6; /* Buffer */
1207 w_tty = 0; /* Omit if no ttys */
1208
1209 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1210 {
1211 int i;
1212
1213 proc = Fcdr (XCAR (tail));
1214 p = XPROCESS (proc);
1215 if (NILP (p->type))
1216 continue;
1217 if (!NILP (query_only) && p->kill_without_query)
1218 continue;
1219 if (STRINGP (p->name)
1220 && ( i = SCHARS (p->name), (i > w_proc)))
1221 w_proc = i;
1222 if (!NILP (p->buffer))
1223 {
1224 if (NILP (XBUFFER (p->buffer)->name))
1225 {
1226 if (w_buffer < 8)
1227 w_buffer = 8; /* (Killed) */
1228 }
1229 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1230 w_buffer = i;
1231 }
1232 if (STRINGP (p->tty_name)
1233 && (i = SCHARS (p->tty_name), (i > w_tty)))
1234 w_tty = i;
1235 }
1236
1237 XSETFASTINT (i_status, w_proc + 1);
1238 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1239 if (w_tty)
1240 {
1241 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1242 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1243 }
1244 else
1245 {
1246 i_tty = Qnil;
1247 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1248 }
1249
1250 XSETFASTINT (minspace, 1);
1251
1252 set_buffer_internal (XBUFFER (Vstandard_output));
1253 current_buffer->undo_list = Qt;
1254
1255 current_buffer->truncate_lines = Qt;
1256
1257 write_string ("Proc", -1);
1258 Findent_to (i_status, minspace); write_string ("Status", -1);
1259 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1260 if (!NILP (i_tty))
1261 {
1262 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1263 }
1264 Findent_to (i_command, minspace); write_string ("Command", -1);
1265 write_string ("\n", -1);
1266
1267 write_string ("----", -1);
1268 Findent_to (i_status, minspace); write_string ("------", -1);
1269 Findent_to (i_buffer, minspace); write_string ("------", -1);
1270 if (!NILP (i_tty))
1271 {
1272 Findent_to (i_tty, minspace); write_string ("---", -1);
1273 }
1274 Findent_to (i_command, minspace); write_string ("-------", -1);
1275 write_string ("\n", -1);
1276
1277 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1278 {
1279 Lisp_Object symbol;
1280
1281 proc = Fcdr (XCAR (tail));
1282 p = XPROCESS (proc);
1283 if (NILP (p->type))
1284 continue;
1285 if (!NILP (query_only) && p->kill_without_query)
1286 continue;
1287
1288 Finsert (1, &p->name);
1289 Findent_to (i_status, minspace);
1290
1291 if (p->raw_status_new)
1292 update_status (p);
1293 symbol = p->status;
1294 if (CONSP (p->status))
1295 symbol = XCAR (p->status);
1296
1297 if (EQ (symbol, Qsignal))
1298 {
1299 Lisp_Object tem;
1300 tem = Fcar (Fcdr (p->status));
1301 Fprinc (symbol, Qnil);
1302 }
1303 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1304 {
1305 if (EQ (symbol, Qexit))
1306 write_string ("closed", -1);
1307 else if (EQ (p->command, Qt))
1308 write_string ("stopped", -1);
1309 else if (EQ (symbol, Qrun))
1310 write_string ("open", -1);
1311 else
1312 Fprinc (symbol, Qnil);
1313 }
1314 else if (SERIALCONN1_P (p))
1315 {
1316 write_string ("running", -1);
1317 }
1318 else
1319 Fprinc (symbol, Qnil);
1320
1321 if (EQ (symbol, Qexit))
1322 {
1323 Lisp_Object tem;
1324 tem = Fcar (Fcdr (p->status));
1325 if (XFASTINT (tem))
1326 {
1327 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1328 write_string (tembuf, -1);
1329 }
1330 }
1331
1332 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1333 exited++;
1334
1335 Findent_to (i_buffer, minspace);
1336 if (NILP (p->buffer))
1337 insert_string ("(none)");
1338 else if (NILP (XBUFFER (p->buffer)->name))
1339 insert_string ("(Killed)");
1340 else
1341 Finsert (1, &XBUFFER (p->buffer)->name);
1342
1343 if (!NILP (i_tty))
1344 {
1345 Findent_to (i_tty, minspace);
1346 if (STRINGP (p->tty_name))
1347 Finsert (1, &p->tty_name);
1348 }
1349
1350 Findent_to (i_command, minspace);
1351
1352 if (EQ (p->status, Qlisten))
1353 {
1354 Lisp_Object port = Fplist_get (p->childp, QCservice);
1355 if (INTEGERP (port))
1356 port = Fnumber_to_string (port);
1357 if (NILP (port))
1358 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1359 sprintf (tembuf, "(network %s server on %s)\n",
1360 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1361 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1362 insert_string (tembuf);
1363 }
1364 else if (NETCONN1_P (p))
1365 {
1366 /* For a local socket, there is no host name,
1367 so display service instead. */
1368 Lisp_Object host = Fplist_get (p->childp, QChost);
1369 if (!STRINGP (host))
1370 {
1371 host = Fplist_get (p->childp, QCservice);
1372 if (INTEGERP (host))
1373 host = Fnumber_to_string (host);
1374 }
1375 if (NILP (host))
1376 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1377 sprintf (tembuf, "(network %s connection to %s)\n",
1378 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1379 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1380 insert_string (tembuf);
1381 }
1382 else if (SERIALCONN1_P (p))
1383 {
1384 Lisp_Object port = Fplist_get (p->childp, QCport);
1385 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1386 insert_string ("(serial port ");
1387 if (STRINGP (port))
1388 insert_string (SDATA (port));
1389 else
1390 insert_string ("?");
1391 if (INTEGERP (speed))
1392 {
1393 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1394 insert_string (tembuf);
1395 }
1396 insert_string (")\n");
1397 }
1398 else
1399 {
1400 tem = p->command;
1401 while (1)
1402 {
1403 tem1 = Fcar (tem);
1404 if (NILP (tem1))
1405 break;
1406 Finsert (1, &tem1);
1407 tem = Fcdr (tem);
1408 if (NILP (tem))
1409 break;
1410 insert_string (" ");
1411 }
1412 insert_string ("\n");
1413 }
1414 }
1415 if (exited)
1416 {
1417 status_notify (NULL);
1418 redisplay_preserve_echo_area (13);
1419 }
1420 return Qnil;
1421 }
1422
1423 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1424 doc: /* Display a list of all processes.
1425 If optional argument QUERY-ONLY is non-nil, only processes with
1426 the query-on-exit flag set will be listed.
1427 Any process listed as exited or signaled is actually eliminated
1428 after the listing is made. */)
1429 (Lisp_Object query_only)
1430 {
1431 internal_with_output_to_temp_buffer ("*Process List*",
1432 list_processes_1, query_only);
1433 return Qnil;
1434 }
1435
1436 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1437 doc: /* Return a list of all processes. */)
1438 (void)
1439 {
1440 return Fmapcar (Qcdr, Vprocess_alist);
1441 }
1442 \f
1443 /* Starting asynchronous inferior processes. */
1444
1445 static Lisp_Object start_process_unwind (Lisp_Object proc);
1446
1447 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1448 doc: /* Start a program in a subprocess. Return the process object for it.
1449 NAME is name for process. It is modified if necessary to make it unique.
1450 BUFFER is the buffer (or buffer name) to associate with the process.
1451
1452 Process output (both standard output and standard error streams) goes
1453 at end of BUFFER, unless you specify an output stream or filter
1454 function to handle the output. BUFFER may also be nil, meaning that
1455 this process is not associated with any buffer.
1456
1457 PROGRAM is the program file name. It is searched for in PATH. If
1458 nil, just associate a pty with the buffer. Remaining arguments are
1459 strings to give program as arguments.
1460
1461 If you want to separate standard output from standard error, invoke
1462 the command through a shell and redirect one of them using the shell
1463 syntax.
1464
1465 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1466 (int nargs, register Lisp_Object *args)
1467 {
1468 Lisp_Object buffer, name, program, proc, current_dir, tem;
1469 register unsigned char **new_argv;
1470 register int i;
1471 int count = SPECPDL_INDEX ();
1472
1473 buffer = args[1];
1474 if (!NILP (buffer))
1475 buffer = Fget_buffer_create (buffer);
1476
1477 /* Make sure that the child will be able to chdir to the current
1478 buffer's current directory, or its unhandled equivalent. We
1479 can't just have the child check for an error when it does the
1480 chdir, since it's in a vfork.
1481
1482 We have to GCPRO around this because Fexpand_file_name and
1483 Funhandled_file_name_directory might call a file name handling
1484 function. The argument list is protected by the caller, so all
1485 we really have to worry about is buffer. */
1486 {
1487 struct gcpro gcpro1, gcpro2;
1488
1489 current_dir = current_buffer->directory;
1490
1491 GCPRO2 (buffer, current_dir);
1492
1493 current_dir = Funhandled_file_name_directory (current_dir);
1494 if (NILP (current_dir))
1495 /* If the file name handler says that current_dir is unreachable, use
1496 a sensible default. */
1497 current_dir = build_string ("~/");
1498 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1499 if (NILP (Ffile_accessible_directory_p (current_dir)))
1500 report_file_error ("Setting current directory",
1501 Fcons (current_buffer->directory, Qnil));
1502
1503 UNGCPRO;
1504 }
1505
1506 name = args[0];
1507 CHECK_STRING (name);
1508
1509 program = args[2];
1510
1511 if (!NILP (program))
1512 CHECK_STRING (program);
1513
1514 proc = make_process (name);
1515 /* If an error occurs and we can't start the process, we want to
1516 remove it from the process list. This means that each error
1517 check in create_process doesn't need to call remove_process
1518 itself; it's all taken care of here. */
1519 record_unwind_protect (start_process_unwind, proc);
1520
1521 XPROCESS (proc)->childp = Qt;
1522 XPROCESS (proc)->plist = Qnil;
1523 XPROCESS (proc)->type = Qreal;
1524 XPROCESS (proc)->buffer = buffer;
1525 XPROCESS (proc)->sentinel = Qnil;
1526 XPROCESS (proc)->filter = Qnil;
1527 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1528
1529 #ifdef ADAPTIVE_READ_BUFFERING
1530 XPROCESS (proc)->adaptive_read_buffering
1531 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1532 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1533 #endif
1534
1535 /* Make the process marker point into the process buffer (if any). */
1536 if (BUFFERP (buffer))
1537 set_marker_both (XPROCESS (proc)->mark, buffer,
1538 BUF_ZV (XBUFFER (buffer)),
1539 BUF_ZV_BYTE (XBUFFER (buffer)));
1540
1541 {
1542 /* Decide coding systems for communicating with the process. Here
1543 we don't setup the structure coding_system nor pay attention to
1544 unibyte mode. They are done in create_process. */
1545
1546 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1547 Lisp_Object coding_systems = Qt;
1548 Lisp_Object val, *args2;
1549 struct gcpro gcpro1, gcpro2;
1550
1551 val = Vcoding_system_for_read;
1552 if (NILP (val))
1553 {
1554 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1555 args2[0] = Qstart_process;
1556 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1557 GCPRO2 (proc, current_dir);
1558 if (!NILP (program))
1559 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1560 UNGCPRO;
1561 if (CONSP (coding_systems))
1562 val = XCAR (coding_systems);
1563 else if (CONSP (Vdefault_process_coding_system))
1564 val = XCAR (Vdefault_process_coding_system);
1565 }
1566 XPROCESS (proc)->decode_coding_system = val;
1567
1568 val = Vcoding_system_for_write;
1569 if (NILP (val))
1570 {
1571 if (EQ (coding_systems, Qt))
1572 {
1573 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1574 args2[0] = Qstart_process;
1575 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1576 GCPRO2 (proc, current_dir);
1577 if (!NILP (program))
1578 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1579 UNGCPRO;
1580 }
1581 if (CONSP (coding_systems))
1582 val = XCDR (coding_systems);
1583 else if (CONSP (Vdefault_process_coding_system))
1584 val = XCDR (Vdefault_process_coding_system);
1585 }
1586 XPROCESS (proc)->encode_coding_system = val;
1587 }
1588
1589
1590 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1591 XPROCESS (proc)->decoding_carryover = 0;
1592 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1593
1594 XPROCESS (proc)->inherit_coding_system_flag
1595 = !(NILP (buffer) || !inherit_process_coding_system);
1596
1597 if (!NILP (program))
1598 {
1599 /* If program file name is not absolute, search our path for it.
1600 Put the name we will really use in TEM. */
1601 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1602 && !(SCHARS (program) > 1
1603 && IS_DEVICE_SEP (SREF (program, 1))))
1604 {
1605 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1606
1607 tem = Qnil;
1608 GCPRO4 (name, program, buffer, current_dir);
1609 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1610 UNGCPRO;
1611 if (NILP (tem))
1612 report_file_error ("Searching for program", Fcons (program, Qnil));
1613 tem = Fexpand_file_name (tem, Qnil);
1614 }
1615 else
1616 {
1617 if (!NILP (Ffile_directory_p (program)))
1618 error ("Specified program for new process is a directory");
1619 tem = program;
1620 }
1621
1622 /* If program file name starts with /: for quoting a magic name,
1623 discard that. */
1624 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1625 && SREF (tem, 1) == ':')
1626 tem = Fsubstring (tem, make_number (2), Qnil);
1627
1628 {
1629 struct gcpro gcpro1;
1630 GCPRO1 (tem);
1631
1632 /* Encode the file name and put it in NEW_ARGV.
1633 That's where the child will use it to execute the program. */
1634 tem = Fcons (ENCODE_FILE (tem), Qnil);
1635
1636 /* Here we encode arguments by the coding system used for sending
1637 data to the process. We don't support using different coding
1638 systems for encoding arguments and for encoding data sent to the
1639 process. */
1640
1641 for (i = 3; i < nargs; i++)
1642 {
1643 tem = Fcons (args[i], tem);
1644 CHECK_STRING (XCAR (tem));
1645 if (STRING_MULTIBYTE (XCAR (tem)))
1646 XSETCAR (tem,
1647 code_convert_string_norecord
1648 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1649 }
1650
1651 UNGCPRO;
1652 }
1653
1654 /* Now that everything is encoded we can collect the strings into
1655 NEW_ARGV. */
1656 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1657 new_argv[nargs - 2] = 0;
1658
1659 for (i = nargs - 3; i >= 0; i--)
1660 {
1661 new_argv[i] = SDATA (XCAR (tem));
1662 tem = XCDR (tem);
1663 }
1664
1665 create_process (proc, (char **) new_argv, current_dir);
1666 }
1667 else
1668 create_pty (proc);
1669
1670 return unbind_to (count, proc);
1671 }
1672
1673 /* This function is the unwind_protect form for Fstart_process. If
1674 PROC doesn't have its pid set, then we know someone has signaled
1675 an error and the process wasn't started successfully, so we should
1676 remove it from the process list. */
1677 static Lisp_Object
1678 start_process_unwind (Lisp_Object proc)
1679 {
1680 if (!PROCESSP (proc))
1681 abort ();
1682
1683 /* Was PROC started successfully? */
1684 if (XPROCESS (proc)->pid == -1)
1685 remove_process (proc);
1686
1687 return Qnil;
1688 }
1689
1690 static void
1691 create_process_1 (struct atimer *timer)
1692 {
1693 /* Nothing to do. */
1694 }
1695
1696
1697 void
1698 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1699 {
1700 int inchannel, outchannel;
1701 pid_t pid;
1702 int sv[2];
1703 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1704 int wait_child_setup[2];
1705 #endif
1706 sigset_t procmask;
1707 sigset_t blocked;
1708 struct sigaction sigint_action;
1709 struct sigaction sigquit_action;
1710 #ifdef AIX
1711 struct sigaction sighup_action;
1712 #endif
1713 /* Use volatile to protect variables from being clobbered by longjmp. */
1714 volatile int forkin, forkout;
1715 volatile int pty_flag = 0;
1716 #ifndef USE_CRT_DLL
1717 extern char **environ;
1718 #endif
1719
1720 inchannel = outchannel = -1;
1721
1722 #ifdef HAVE_PTYS
1723 if (!NILP (Vprocess_connection_type))
1724 outchannel = inchannel = allocate_pty ();
1725
1726 if (inchannel >= 0)
1727 {
1728 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1729 /* On most USG systems it does not work to open the pty's tty here,
1730 then close it and reopen it in the child. */
1731 #ifdef O_NOCTTY
1732 /* Don't let this terminal become our controlling terminal
1733 (in case we don't have one). */
1734 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1735 #else
1736 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1737 #endif
1738 if (forkin < 0)
1739 report_file_error ("Opening pty", Qnil);
1740 #else
1741 forkin = forkout = -1;
1742 #endif /* not USG, or USG_SUBTTY_WORKS */
1743 pty_flag = 1;
1744 }
1745 else
1746 #endif /* HAVE_PTYS */
1747 {
1748 int tem;
1749 tem = pipe (sv);
1750 if (tem < 0)
1751 report_file_error ("Creating pipe", Qnil);
1752 inchannel = sv[0];
1753 forkout = sv[1];
1754 tem = pipe (sv);
1755 if (tem < 0)
1756 {
1757 emacs_close (inchannel);
1758 emacs_close (forkout);
1759 report_file_error ("Creating pipe", Qnil);
1760 }
1761 outchannel = sv[1];
1762 forkin = sv[0];
1763 }
1764
1765 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1766 {
1767 int tem;
1768
1769 tem = pipe (wait_child_setup);
1770 if (tem < 0)
1771 report_file_error ("Creating pipe", Qnil);
1772 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1773 if (tem >= 0)
1774 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1775 if (tem < 0)
1776 {
1777 emacs_close (wait_child_setup[0]);
1778 emacs_close (wait_child_setup[1]);
1779 report_file_error ("Setting file descriptor flags", Qnil);
1780 }
1781 }
1782 #endif
1783
1784 #if 0
1785 /* Replaced by close_process_descs */
1786 set_exclusive_use (inchannel);
1787 set_exclusive_use (outchannel);
1788 #endif
1789
1790 #ifdef O_NONBLOCK
1791 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1792 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1793 #else
1794 #ifdef O_NDELAY
1795 fcntl (inchannel, F_SETFL, O_NDELAY);
1796 fcntl (outchannel, F_SETFL, O_NDELAY);
1797 #endif
1798 #endif
1799
1800 /* Record this as an active process, with its channels.
1801 As a result, child_setup will close Emacs's side of the pipes. */
1802 chan_process[inchannel] = process;
1803 XPROCESS (process)->infd = inchannel;
1804 XPROCESS (process)->outfd = outchannel;
1805
1806 /* Previously we recorded the tty descriptor used in the subprocess.
1807 It was only used for getting the foreground tty process, so now
1808 we just reopen the device (see emacs_get_tty_pgrp) as this is
1809 more portable (see USG_SUBTTY_WORKS above). */
1810
1811 XPROCESS (process)->pty_flag = pty_flag;
1812 XPROCESS (process)->status = Qrun;
1813 setup_process_coding_systems (process);
1814
1815 /* Delay interrupts until we have a chance to store
1816 the new fork's pid in its process structure */
1817 sigemptyset (&blocked);
1818 #ifdef SIGCHLD
1819 sigaddset (&blocked, SIGCHLD);
1820 #endif
1821 #ifdef HAVE_WORKING_VFORK
1822 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1823 this sets the parent's signal handlers as well as the child's.
1824 So delay all interrupts whose handlers the child might munge,
1825 and record the current handlers so they can be restored later. */
1826 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1827 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1828 #ifdef AIX
1829 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1830 #endif
1831 #endif /* HAVE_WORKING_VFORK */
1832 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1833
1834 FD_SET (inchannel, &input_wait_mask);
1835 FD_SET (inchannel, &non_keyboard_wait_mask);
1836 if (inchannel > max_process_desc)
1837 max_process_desc = inchannel;
1838
1839 /* Until we store the proper pid, enable sigchld_handler
1840 to recognize an unknown pid as standing for this process.
1841 It is very important not to let this `marker' value stay
1842 in the table after this function has returned; if it does
1843 it might cause call-process to hang and subsequent asynchronous
1844 processes to get their return values scrambled. */
1845 XPROCESS (process)->pid = -1;
1846
1847 BLOCK_INPUT;
1848
1849 {
1850 /* child_setup must clobber environ on systems with true vfork.
1851 Protect it from permanent change. */
1852 char **save_environ = environ;
1853
1854 current_dir = ENCODE_FILE (current_dir);
1855
1856 #ifndef WINDOWSNT
1857 pid = vfork ();
1858 if (pid == 0)
1859 #endif /* not WINDOWSNT */
1860 {
1861 int xforkin = forkin;
1862 int xforkout = forkout;
1863
1864 #if 0 /* This was probably a mistake--it duplicates code later on,
1865 but fails to handle all the cases. */
1866 /* Make sure SIGCHLD is not blocked in the child. */
1867 sigsetmask (SIGEMPTYMASK);
1868 #endif
1869
1870 /* Make the pty be the controlling terminal of the process. */
1871 #ifdef HAVE_PTYS
1872 /* First, disconnect its current controlling terminal. */
1873 #ifdef HAVE_SETSID
1874 /* We tried doing setsid only if pty_flag, but it caused
1875 process_set_signal to fail on SGI when using a pipe. */
1876 setsid ();
1877 /* Make the pty's terminal the controlling terminal. */
1878 if (pty_flag && xforkin >= 0)
1879 {
1880 #ifdef TIOCSCTTY
1881 /* We ignore the return value
1882 because faith@cs.unc.edu says that is necessary on Linux. */
1883 ioctl (xforkin, TIOCSCTTY, 0);
1884 #endif
1885 }
1886 #else /* not HAVE_SETSID */
1887 #ifdef USG
1888 /* It's very important to call setpgrp here and no time
1889 afterwards. Otherwise, we lose our controlling tty which
1890 is set when we open the pty. */
1891 setpgrp ();
1892 #endif /* USG */
1893 #endif /* not HAVE_SETSID */
1894 #if defined (LDISC1)
1895 if (pty_flag && xforkin >= 0)
1896 {
1897 struct termios t;
1898 tcgetattr (xforkin, &t);
1899 t.c_lflag = LDISC1;
1900 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1901 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1902 }
1903 #else
1904 #if defined (NTTYDISC) && defined (TIOCSETD)
1905 if (pty_flag && xforkin >= 0)
1906 {
1907 /* Use new line discipline. */
1908 int ldisc = NTTYDISC;
1909 ioctl (xforkin, TIOCSETD, &ldisc);
1910 }
1911 #endif
1912 #endif
1913 #ifdef TIOCNOTTY
1914 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1915 can do TIOCSPGRP only to the process's controlling tty. */
1916 if (pty_flag)
1917 {
1918 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1919 I can't test it since I don't have 4.3. */
1920 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1921 if (j >= 0)
1922 {
1923 ioctl (j, TIOCNOTTY, 0);
1924 emacs_close (j);
1925 }
1926 #ifndef USG
1927 /* In order to get a controlling terminal on some versions
1928 of BSD, it is necessary to put the process in pgrp 0
1929 before it opens the terminal. */
1930 #ifdef HAVE_SETPGID
1931 setpgid (0, 0);
1932 #else
1933 setpgrp (0, 0);
1934 #endif
1935 #endif
1936 }
1937 #endif /* TIOCNOTTY */
1938
1939 #if !defined (DONT_REOPEN_PTY)
1940 /*** There is a suggestion that this ought to be a
1941 conditional on TIOCSPGRP,
1942 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1943 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1944 that system does seem to need this code, even though
1945 both HAVE_SETSID and TIOCSCTTY are defined. */
1946 /* Now close the pty (if we had it open) and reopen it.
1947 This makes the pty the controlling terminal of the subprocess. */
1948 if (pty_flag)
1949 {
1950
1951 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1952 would work? */
1953 if (xforkin >= 0)
1954 emacs_close (xforkin);
1955 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1956
1957 if (xforkin < 0)
1958 {
1959 emacs_write (1, "Couldn't open the pty terminal ", 31);
1960 emacs_write (1, pty_name, strlen (pty_name));
1961 emacs_write (1, "\n", 1);
1962 _exit (1);
1963 }
1964
1965 }
1966 #endif /* not DONT_REOPEN_PTY */
1967
1968 #ifdef SETUP_SLAVE_PTY
1969 if (pty_flag)
1970 {
1971 SETUP_SLAVE_PTY;
1972 }
1973 #endif /* SETUP_SLAVE_PTY */
1974 #ifdef AIX
1975 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1976 Now reenable it in the child, so it will die when we want it to. */
1977 if (pty_flag)
1978 signal (SIGHUP, SIG_DFL);
1979 #endif
1980 #endif /* HAVE_PTYS */
1981
1982 signal (SIGINT, SIG_DFL);
1983 signal (SIGQUIT, SIG_DFL);
1984
1985 /* Stop blocking signals in the child. */
1986 sigprocmask (SIG_SETMASK, &procmask, 0);
1987
1988 if (pty_flag)
1989 child_setup_tty (xforkout);
1990 #ifdef WINDOWSNT
1991 pid = child_setup (xforkin, xforkout, xforkout,
1992 new_argv, 1, current_dir);
1993 #else /* not WINDOWSNT */
1994 #ifdef FD_CLOEXEC
1995 emacs_close (wait_child_setup[0]);
1996 #endif
1997 child_setup (xforkin, xforkout, xforkout,
1998 new_argv, 1, current_dir);
1999 #endif /* not WINDOWSNT */
2000 }
2001 environ = save_environ;
2002 }
2003
2004 UNBLOCK_INPUT;
2005
2006 /* This runs in the Emacs process. */
2007 if (pid < 0)
2008 {
2009 if (forkin >= 0)
2010 emacs_close (forkin);
2011 if (forkin != forkout && forkout >= 0)
2012 emacs_close (forkout);
2013 }
2014 else
2015 {
2016 /* vfork succeeded. */
2017 XPROCESS (process)->pid = pid;
2018
2019 #ifdef WINDOWSNT
2020 register_child (pid, inchannel);
2021 #endif /* WINDOWSNT */
2022
2023 /* If the subfork execv fails, and it exits,
2024 this close hangs. I don't know why.
2025 So have an interrupt jar it loose. */
2026 {
2027 struct atimer *timer;
2028 EMACS_TIME offset;
2029
2030 stop_polling ();
2031 EMACS_SET_SECS_USECS (offset, 1, 0);
2032 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2033
2034 if (forkin >= 0)
2035 emacs_close (forkin);
2036
2037 cancel_atimer (timer);
2038 start_polling ();
2039 }
2040
2041 if (forkin != forkout && forkout >= 0)
2042 emacs_close (forkout);
2043
2044 #ifdef HAVE_PTYS
2045 if (pty_flag)
2046 XPROCESS (process)->tty_name = build_string (pty_name);
2047 else
2048 #endif
2049 XPROCESS (process)->tty_name = Qnil;
2050
2051 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2052 /* Wait for child_setup to complete in case that vfork is
2053 actually defined as fork. The descriptor wait_child_setup[1]
2054 of a pipe is closed at the child side either by close-on-exec
2055 on successful execvp or the _exit call in child_setup. */
2056 {
2057 char dummy;
2058
2059 emacs_close (wait_child_setup[1]);
2060 emacs_read (wait_child_setup[0], &dummy, 1);
2061 emacs_close (wait_child_setup[0]);
2062 }
2063 #endif
2064 }
2065
2066 /* Restore the signal state whether vfork succeeded or not.
2067 (We will signal an error, below, if it failed.) */
2068 #ifdef HAVE_WORKING_VFORK
2069 /* Restore the parent's signal handlers. */
2070 sigaction (SIGINT, &sigint_action, 0);
2071 sigaction (SIGQUIT, &sigquit_action, 0);
2072 #ifdef AIX
2073 sigaction (SIGHUP, &sighup_action, 0);
2074 #endif
2075 #endif /* HAVE_WORKING_VFORK */
2076 /* Stop blocking signals in the parent. */
2077 sigprocmask (SIG_SETMASK, &procmask, 0);
2078
2079 /* Now generate the error if vfork failed. */
2080 if (pid < 0)
2081 report_file_error ("Doing vfork", Qnil);
2082 }
2083
2084 void
2085 create_pty (Lisp_Object process)
2086 {
2087 int inchannel, outchannel;
2088
2089 /* Use volatile to protect variables from being clobbered by longjmp. */
2090 volatile int forkin, forkout;
2091 volatile int pty_flag = 0;
2092
2093 inchannel = outchannel = -1;
2094
2095 #ifdef HAVE_PTYS
2096 if (!NILP (Vprocess_connection_type))
2097 outchannel = inchannel = allocate_pty ();
2098
2099 if (inchannel >= 0)
2100 {
2101 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2102 /* On most USG systems it does not work to open the pty's tty here,
2103 then close it and reopen it in the child. */
2104 #ifdef O_NOCTTY
2105 /* Don't let this terminal become our controlling terminal
2106 (in case we don't have one). */
2107 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2108 #else
2109 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2110 #endif
2111 if (forkin < 0)
2112 report_file_error ("Opening pty", Qnil);
2113 #if defined (DONT_REOPEN_PTY)
2114 /* In the case that vfork is defined as fork, the parent process
2115 (Emacs) may send some data before the child process completes
2116 tty options setup. So we setup tty before forking. */
2117 child_setup_tty (forkout);
2118 #endif /* DONT_REOPEN_PTY */
2119 #else
2120 forkin = forkout = -1;
2121 #endif /* not USG, or USG_SUBTTY_WORKS */
2122 pty_flag = 1;
2123 }
2124 #endif /* HAVE_PTYS */
2125
2126 #ifdef O_NONBLOCK
2127 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2128 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2129 #else
2130 #ifdef O_NDELAY
2131 fcntl (inchannel, F_SETFL, O_NDELAY);
2132 fcntl (outchannel, F_SETFL, O_NDELAY);
2133 #endif
2134 #endif
2135
2136 /* Record this as an active process, with its channels.
2137 As a result, child_setup will close Emacs's side of the pipes. */
2138 chan_process[inchannel] = process;
2139 XPROCESS (process)->infd = inchannel;
2140 XPROCESS (process)->outfd = outchannel;
2141
2142 /* Previously we recorded the tty descriptor used in the subprocess.
2143 It was only used for getting the foreground tty process, so now
2144 we just reopen the device (see emacs_get_tty_pgrp) as this is
2145 more portable (see USG_SUBTTY_WORKS above). */
2146
2147 XPROCESS (process)->pty_flag = pty_flag;
2148 XPROCESS (process)->status = Qrun;
2149 setup_process_coding_systems (process);
2150
2151 FD_SET (inchannel, &input_wait_mask);
2152 FD_SET (inchannel, &non_keyboard_wait_mask);
2153 if (inchannel > max_process_desc)
2154 max_process_desc = inchannel;
2155
2156 XPROCESS (process)->pid = -2;
2157 #ifdef HAVE_PTYS
2158 if (pty_flag)
2159 XPROCESS (process)->tty_name = build_string (pty_name);
2160 else
2161 #endif
2162 XPROCESS (process)->tty_name = Qnil;
2163 }
2164
2165 \f
2166 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2167 The address family of sa is not included in the result. */
2168
2169 static Lisp_Object
2170 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2171 {
2172 Lisp_Object address;
2173 int i;
2174 unsigned char *cp;
2175 register struct Lisp_Vector *p;
2176
2177 /* Workaround for a bug in getsockname on BSD: Names bound to
2178 sockets in the UNIX domain are inaccessible; getsockname returns
2179 a zero length name. */
2180 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2181 return empty_unibyte_string;
2182
2183 switch (sa->sa_family)
2184 {
2185 case AF_INET:
2186 {
2187 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2188 len = sizeof (sin->sin_addr) + 1;
2189 address = Fmake_vector (make_number (len), Qnil);
2190 p = XVECTOR (address);
2191 p->contents[--len] = make_number (ntohs (sin->sin_port));
2192 cp = (unsigned char *) &sin->sin_addr;
2193 break;
2194 }
2195 #ifdef AF_INET6
2196 case AF_INET6:
2197 {
2198 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2199 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2200 len = sizeof (sin6->sin6_addr)/2 + 1;
2201 address = Fmake_vector (make_number (len), Qnil);
2202 p = XVECTOR (address);
2203 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2204 for (i = 0; i < len; i++)
2205 p->contents[i] = make_number (ntohs (ip6[i]));
2206 return address;
2207 }
2208 #endif
2209 #ifdef HAVE_LOCAL_SOCKETS
2210 case AF_LOCAL:
2211 {
2212 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2213 for (i = 0; i < sizeof (sockun->sun_path); i++)
2214 if (sockun->sun_path[i] == 0)
2215 break;
2216 return make_unibyte_string (sockun->sun_path, i);
2217 }
2218 #endif
2219 default:
2220 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2221 address = Fcons (make_number (sa->sa_family),
2222 Fmake_vector (make_number (len), Qnil));
2223 p = XVECTOR (XCDR (address));
2224 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2225 break;
2226 }
2227
2228 i = 0;
2229 while (i < len)
2230 p->contents[i++] = make_number (*cp++);
2231
2232 return address;
2233 }
2234
2235
2236 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2237
2238 static int
2239 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2240 {
2241 register struct Lisp_Vector *p;
2242
2243 if (VECTORP (address))
2244 {
2245 p = XVECTOR (address);
2246 if (p->size == 5)
2247 {
2248 *familyp = AF_INET;
2249 return sizeof (struct sockaddr_in);
2250 }
2251 #ifdef AF_INET6
2252 else if (p->size == 9)
2253 {
2254 *familyp = AF_INET6;
2255 return sizeof (struct sockaddr_in6);
2256 }
2257 #endif
2258 }
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 else if (STRINGP (address))
2261 {
2262 *familyp = AF_LOCAL;
2263 return sizeof (struct sockaddr_un);
2264 }
2265 #endif
2266 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2267 {
2268 struct sockaddr *sa;
2269 *familyp = XINT (XCAR (address));
2270 p = XVECTOR (XCDR (address));
2271 return p->size + sizeof (sa->sa_family);
2272 }
2273 return 0;
2274 }
2275
2276 /* Convert an address object (vector or string) to an internal sockaddr.
2277
2278 The address format has been basically validated by
2279 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2280 it could have come from user data. So if FAMILY is not valid,
2281 we return after zeroing *SA. */
2282
2283 static void
2284 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2285 {
2286 register struct Lisp_Vector *p;
2287 register unsigned char *cp = NULL;
2288 register int i;
2289
2290 memset (sa, 0, len);
2291
2292 if (VECTORP (address))
2293 {
2294 p = XVECTOR (address);
2295 if (family == AF_INET)
2296 {
2297 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2298 len = sizeof (sin->sin_addr) + 1;
2299 i = XINT (p->contents[--len]);
2300 sin->sin_port = htons (i);
2301 cp = (unsigned char *)&sin->sin_addr;
2302 sa->sa_family = family;
2303 }
2304 #ifdef AF_INET6
2305 else if (family == AF_INET6)
2306 {
2307 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2308 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2309 len = sizeof (sin6->sin6_addr) + 1;
2310 i = XINT (p->contents[--len]);
2311 sin6->sin6_port = htons (i);
2312 for (i = 0; i < len; i++)
2313 if (INTEGERP (p->contents[i]))
2314 {
2315 int j = XFASTINT (p->contents[i]) & 0xffff;
2316 ip6[i] = ntohs (j);
2317 }
2318 sa->sa_family = family;
2319 return;
2320 }
2321 #endif
2322 else
2323 return;
2324 }
2325 else if (STRINGP (address))
2326 {
2327 #ifdef HAVE_LOCAL_SOCKETS
2328 if (family == AF_LOCAL)
2329 {
2330 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2331 cp = SDATA (address);
2332 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2333 sockun->sun_path[i] = *cp++;
2334 sa->sa_family = family;
2335 }
2336 #endif
2337 return;
2338 }
2339 else
2340 {
2341 p = XVECTOR (XCDR (address));
2342 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2343 }
2344
2345 for (i = 0; i < len; i++)
2346 if (INTEGERP (p->contents[i]))
2347 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2348 }
2349
2350 #ifdef DATAGRAM_SOCKETS
2351 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2352 1, 1, 0,
2353 doc: /* Get the current datagram address associated with PROCESS. */)
2354 (Lisp_Object process)
2355 {
2356 int channel;
2357
2358 CHECK_PROCESS (process);
2359
2360 if (!DATAGRAM_CONN_P (process))
2361 return Qnil;
2362
2363 channel = XPROCESS (process)->infd;
2364 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2365 datagram_address[channel].len);
2366 }
2367
2368 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2369 2, 2, 0,
2370 doc: /* Set the datagram address for PROCESS to ADDRESS.
2371 Returns nil upon error setting address, ADDRESS otherwise. */)
2372 (Lisp_Object process, Lisp_Object address)
2373 {
2374 int channel;
2375 int family, len;
2376
2377 CHECK_PROCESS (process);
2378
2379 if (!DATAGRAM_CONN_P (process))
2380 return Qnil;
2381
2382 channel = XPROCESS (process)->infd;
2383
2384 len = get_lisp_to_sockaddr_size (address, &family);
2385 if (datagram_address[channel].len != len)
2386 return Qnil;
2387 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2388 return address;
2389 }
2390 #endif
2391 \f
2392
2393 static const struct socket_options {
2394 /* The name of this option. Should be lowercase version of option
2395 name without SO_ prefix. */
2396 const char *name;
2397 /* Option level SOL_... */
2398 int optlevel;
2399 /* Option number SO_... */
2400 int optnum;
2401 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2402 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2403 } socket_options[] =
2404 {
2405 #ifdef SO_BINDTODEVICE
2406 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2407 #endif
2408 #ifdef SO_BROADCAST
2409 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2410 #endif
2411 #ifdef SO_DONTROUTE
2412 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2413 #endif
2414 #ifdef SO_KEEPALIVE
2415 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2416 #endif
2417 #ifdef SO_LINGER
2418 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2419 #endif
2420 #ifdef SO_OOBINLINE
2421 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2422 #endif
2423 #ifdef SO_PRIORITY
2424 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2425 #endif
2426 #ifdef SO_REUSEADDR
2427 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2428 #endif
2429 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2430 };
2431
2432 /* Set option OPT to value VAL on socket S.
2433
2434 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2435 Signals an error if setting a known option fails.
2436 */
2437
2438 static int
2439 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2440 {
2441 char *name;
2442 const struct socket_options *sopt;
2443 int ret = 0;
2444
2445 CHECK_SYMBOL (opt);
2446
2447 name = (char *) SDATA (SYMBOL_NAME (opt));
2448 for (sopt = socket_options; sopt->name; sopt++)
2449 if (strcmp (name, sopt->name) == 0)
2450 break;
2451
2452 switch (sopt->opttype)
2453 {
2454 case SOPT_BOOL:
2455 {
2456 int optval;
2457 optval = NILP (val) ? 0 : 1;
2458 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2459 &optval, sizeof (optval));
2460 break;
2461 }
2462
2463 case SOPT_INT:
2464 {
2465 int optval;
2466 if (INTEGERP (val))
2467 optval = XINT (val);
2468 else
2469 error ("Bad option value for %s", name);
2470 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2471 &optval, sizeof (optval));
2472 break;
2473 }
2474
2475 #ifdef SO_BINDTODEVICE
2476 case SOPT_IFNAME:
2477 {
2478 char devname[IFNAMSIZ+1];
2479
2480 /* This is broken, at least in the Linux 2.4 kernel.
2481 To unbind, the arg must be a zero integer, not the empty string.
2482 This should work on all systems. KFS. 2003-09-23. */
2483 memset (devname, 0, sizeof devname);
2484 if (STRINGP (val))
2485 {
2486 char *arg = (char *) SDATA (val);
2487 int len = min (strlen (arg), IFNAMSIZ);
2488 memcpy (devname, arg, len);
2489 }
2490 else if (!NILP (val))
2491 error ("Bad option value for %s", name);
2492 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2493 devname, IFNAMSIZ);
2494 break;
2495 }
2496 #endif
2497
2498 #ifdef SO_LINGER
2499 case SOPT_LINGER:
2500 {
2501 struct linger linger;
2502
2503 linger.l_onoff = 1;
2504 linger.l_linger = 0;
2505 if (INTEGERP (val))
2506 linger.l_linger = XINT (val);
2507 else
2508 linger.l_onoff = NILP (val) ? 0 : 1;
2509 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2510 &linger, sizeof (linger));
2511 break;
2512 }
2513 #endif
2514
2515 default:
2516 return 0;
2517 }
2518
2519 if (ret < 0)
2520 report_file_error ("Cannot set network option",
2521 Fcons (opt, Fcons (val, Qnil)));
2522 return (1 << sopt->optbit);
2523 }
2524
2525
2526 DEFUN ("set-network-process-option",
2527 Fset_network_process_option, Sset_network_process_option,
2528 3, 4, 0,
2529 doc: /* For network process PROCESS set option OPTION to value VALUE.
2530 See `make-network-process' for a list of options and values.
2531 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2532 OPTION is not a supported option, return nil instead; otherwise return t. */)
2533 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2534 {
2535 int s;
2536 struct Lisp_Process *p;
2537
2538 CHECK_PROCESS (process);
2539 p = XPROCESS (process);
2540 if (!NETCONN1_P (p))
2541 error ("Process is not a network process");
2542
2543 s = p->infd;
2544 if (s < 0)
2545 error ("Process is not running");
2546
2547 if (set_socket_option (s, option, value))
2548 {
2549 p->childp = Fplist_put (p->childp, option, value);
2550 return Qt;
2551 }
2552
2553 if (NILP (no_error))
2554 error ("Unknown or unsupported option");
2555
2556 return Qnil;
2557 }
2558
2559 \f
2560 DEFUN ("serial-process-configure",
2561 Fserial_process_configure,
2562 Sserial_process_configure,
2563 0, MANY, 0,
2564 doc: /* Configure speed, bytesize, etc. of a serial process.
2565
2566 Arguments are specified as keyword/argument pairs. Attributes that
2567 are not given are re-initialized from the process's current
2568 configuration (available via the function `process-contact') or set to
2569 reasonable default values. The following arguments are defined:
2570
2571 :process PROCESS
2572 :name NAME
2573 :buffer BUFFER
2574 :port PORT
2575 -- Any of these arguments can be given to identify the process that is
2576 to be configured. If none of these arguments is given, the current
2577 buffer's process is used.
2578
2579 :speed SPEED -- SPEED is the speed of the serial port in bits per
2580 second, also called baud rate. Any value can be given for SPEED, but
2581 most serial ports work only at a few defined values between 1200 and
2582 115200, with 9600 being the most common value. If SPEED is nil, the
2583 serial port is not configured any further, i.e., all other arguments
2584 are ignored. This may be useful for special serial ports such as
2585 Bluetooth-to-serial converters which can only be configured through AT
2586 commands. A value of nil for SPEED can be used only when passed
2587 through `make-serial-process' or `serial-term'.
2588
2589 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2590 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2591
2592 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2593 `odd' (use odd parity), or the symbol `even' (use even parity). If
2594 PARITY is not given, no parity is used.
2595
2596 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2597 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2598 is not given or nil, 1 stopbit is used.
2599
2600 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2601 flowcontrol to be used, which is either nil (don't use flowcontrol),
2602 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2603 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2604 flowcontrol is used.
2605
2606 `serial-process-configure' is called by `make-serial-process' for the
2607 initial configuration of the serial port.
2608
2609 Examples:
2610
2611 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2612
2613 \(serial-process-configure
2614 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2615
2616 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2617
2618 usage: (serial-process-configure &rest ARGS) */)
2619 (int nargs, Lisp_Object *args)
2620 {
2621 struct Lisp_Process *p;
2622 Lisp_Object contact = Qnil;
2623 Lisp_Object proc = Qnil;
2624 struct gcpro gcpro1;
2625
2626 contact = Flist (nargs, args);
2627 GCPRO1 (contact);
2628
2629 proc = Fplist_get (contact, QCprocess);
2630 if (NILP (proc))
2631 proc = Fplist_get (contact, QCname);
2632 if (NILP (proc))
2633 proc = Fplist_get (contact, QCbuffer);
2634 if (NILP (proc))
2635 proc = Fplist_get (contact, QCport);
2636 proc = get_process (proc);
2637 p = XPROCESS (proc);
2638 if (!EQ (p->type, Qserial))
2639 error ("Not a serial process");
2640
2641 if (NILP (Fplist_get (p->childp, QCspeed)))
2642 {
2643 UNGCPRO;
2644 return Qnil;
2645 }
2646
2647 serial_configure (p, contact);
2648
2649 UNGCPRO;
2650 return Qnil;
2651 }
2652
2653 /* Used by make-serial-process to recover from errors. */
2654 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2655 {
2656 if (!PROCESSP (proc))
2657 abort ();
2658 remove_process (proc);
2659 return Qnil;
2660 }
2661
2662 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2663 0, MANY, 0,
2664 doc: /* Create and return a serial port process.
2665
2666 In Emacs, serial port connections are represented by process objects,
2667 so input and output work as for subprocesses, and `delete-process'
2668 closes a serial port connection. However, a serial process has no
2669 process id, it cannot be signaled, and the status codes are different
2670 from normal processes.
2671
2672 `make-serial-process' creates a process and a buffer, on which you
2673 probably want to use `process-send-string'. Try \\[serial-term] for
2674 an interactive terminal. See below for examples.
2675
2676 Arguments are specified as keyword/argument pairs. The following
2677 arguments are defined:
2678
2679 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2680 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2681 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2682 the backslashes in strings).
2683
2684 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2685 which is called by `make-serial-process'.
2686
2687 :name NAME -- NAME is the name of the process. If NAME is not given,
2688 the value of PORT is used.
2689
2690 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2691 with the process. Process output goes at the end of that buffer,
2692 unless you specify an output stream or filter function to handle the
2693 output. If BUFFER is not given, the value of NAME is used.
2694
2695 :coding CODING -- If CODING is a symbol, it specifies the coding
2696 system used for both reading and writing for this process. If CODING
2697 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2698 ENCODING is used for writing.
2699
2700 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2701 the process is running. If BOOL is not given, query before exiting.
2702
2703 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2704 In the stopped state, a serial process does not accept incoming data,
2705 but you can send outgoing data. The stopped state is cleared by
2706 `continue-process' and set by `stop-process'.
2707
2708 :filter FILTER -- Install FILTER as the process filter.
2709
2710 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2711
2712 :plist PLIST -- Install PLIST as the initial plist of the process.
2713
2714 :speed
2715 :bytesize
2716 :parity
2717 :stopbits
2718 :flowcontrol
2719 -- These arguments are handled by `serial-process-configure', which is
2720 called by `make-serial-process'.
2721
2722 The original argument list, possibly modified by later configuration,
2723 is available via the function `process-contact'.
2724
2725 Examples:
2726
2727 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2728
2729 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2730
2731 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2732
2733 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2734
2735 usage: (make-serial-process &rest ARGS) */)
2736 (int nargs, Lisp_Object *args)
2737 {
2738 int fd = -1;
2739 Lisp_Object proc, contact, port;
2740 struct Lisp_Process *p;
2741 struct gcpro gcpro1;
2742 Lisp_Object name, buffer;
2743 Lisp_Object tem, val;
2744 int specpdl_count = -1;
2745
2746 if (nargs == 0)
2747 return Qnil;
2748
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2751
2752 port = Fplist_get (contact, QCport);
2753 if (NILP (port))
2754 error ("No port specified");
2755 CHECK_STRING (port);
2756
2757 if (NILP (Fplist_member (contact, QCspeed)))
2758 error (":speed not specified");
2759 if (!NILP (Fplist_get (contact, QCspeed)))
2760 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2761
2762 name = Fplist_get (contact, QCname);
2763 if (NILP (name))
2764 name = port;
2765 CHECK_STRING (name);
2766 proc = make_process (name);
2767 specpdl_count = SPECPDL_INDEX ();
2768 record_unwind_protect (make_serial_process_unwind, proc);
2769 p = XPROCESS (proc);
2770
2771 fd = serial_open ((char*) SDATA (port));
2772 p->infd = fd;
2773 p->outfd = fd;
2774 if (fd > max_process_desc)
2775 max_process_desc = fd;
2776 chan_process[fd] = proc;
2777
2778 buffer = Fplist_get (contact, QCbuffer);
2779 if (NILP (buffer))
2780 buffer = name;
2781 buffer = Fget_buffer_create (buffer);
2782 p->buffer = buffer;
2783
2784 p->childp = contact;
2785 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2786 p->type = Qserial;
2787 p->sentinel = Fplist_get (contact, QCsentinel);
2788 p->filter = Fplist_get (contact, QCfilter);
2789 p->log = Qnil;
2790 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2791 p->kill_without_query = 1;
2792 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2793 p->command = Qt;
2794 p->pty_flag = 0;
2795
2796 if (!EQ (p->command, Qt))
2797 {
2798 FD_SET (fd, &input_wait_mask);
2799 FD_SET (fd, &non_keyboard_wait_mask);
2800 }
2801
2802 if (BUFFERP (buffer))
2803 {
2804 set_marker_both (p->mark, buffer,
2805 BUF_ZV (XBUFFER (buffer)),
2806 BUF_ZV_BYTE (XBUFFER (buffer)));
2807 }
2808
2809 tem = Fplist_member (contact, QCcoding);
2810 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2811 tem = Qnil;
2812
2813 val = Qnil;
2814 if (!NILP (tem))
2815 {
2816 val = XCAR (XCDR (tem));
2817 if (CONSP (val))
2818 val = XCAR (val);
2819 }
2820 else if (!NILP (Vcoding_system_for_read))
2821 val = Vcoding_system_for_read;
2822 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2823 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2824 val = Qnil;
2825 p->decode_coding_system = val;
2826
2827 val = Qnil;
2828 if (!NILP (tem))
2829 {
2830 val = XCAR (XCDR (tem));
2831 if (CONSP (val))
2832 val = XCDR (val);
2833 }
2834 else if (!NILP (Vcoding_system_for_write))
2835 val = Vcoding_system_for_write;
2836 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2837 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2838 val = Qnil;
2839 p->encode_coding_system = val;
2840
2841 setup_process_coding_systems (proc);
2842 p->decoding_buf = make_uninit_string (0);
2843 p->decoding_carryover = 0;
2844 p->encoding_buf = make_uninit_string (0);
2845 p->inherit_coding_system_flag
2846 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2847
2848 Fserial_process_configure (nargs, args);
2849
2850 specpdl_ptr = specpdl + specpdl_count;
2851
2852 UNGCPRO;
2853 return proc;
2854 }
2855
2856 /* Create a network stream/datagram client/server process. Treated
2857 exactly like a normal process when reading and writing. Primary
2858 differences are in status display and process deletion. A network
2859 connection has no PID; you cannot signal it. All you can do is
2860 stop/continue it and deactivate/close it via delete-process */
2861
2862 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2863 0, MANY, 0,
2864 doc: /* Create and return a network server or client process.
2865
2866 In Emacs, network connections are represented by process objects, so
2867 input and output work as for subprocesses and `delete-process' closes
2868 a network connection. However, a network process has no process id,
2869 it cannot be signaled, and the status codes are different from normal
2870 processes.
2871
2872 Arguments are specified as keyword/argument pairs. The following
2873 arguments are defined:
2874
2875 :name NAME -- NAME is name for process. It is modified if necessary
2876 to make it unique.
2877
2878 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2879 with the process. Process output goes at end of that buffer, unless
2880 you specify an output stream or filter function to handle the output.
2881 BUFFER may be also nil, meaning that this process is not associated
2882 with any buffer.
2883
2884 :host HOST -- HOST is name of the host to connect to, or its IP
2885 address. The symbol `local' specifies the local host. If specified
2886 for a server process, it must be a valid name or address for the local
2887 host, and only clients connecting to that address will be accepted.
2888
2889 :service SERVICE -- SERVICE is name of the service desired, or an
2890 integer specifying a port number to connect to. If SERVICE is t,
2891 a random port number is selected for the server. (If Emacs was
2892 compiled with getaddrinfo, a port number can also be specified as a
2893 string, e.g. "80", as well as an integer. This is not portable.)
2894
2895 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2896 stream type connection, `datagram' creates a datagram type connection,
2897 `seqpacket' creates a reliable datagram connection.
2898
2899 :family FAMILY -- FAMILY is the address (and protocol) family for the
2900 service specified by HOST and SERVICE. The default (nil) is to use
2901 whatever address family (IPv4 or IPv6) that is defined for the host
2902 and port number specified by HOST and SERVICE. Other address families
2903 supported are:
2904 local -- for a local (i.e. UNIX) address specified by SERVICE.
2905 ipv4 -- use IPv4 address family only.
2906 ipv6 -- use IPv6 address family only.
2907
2908 :local ADDRESS -- ADDRESS is the local address used for the connection.
2909 This parameter is ignored when opening a client process. When specified
2910 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2911
2912 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2913 connection. This parameter is ignored when opening a stream server
2914 process. For a datagram server process, it specifies the initial
2915 setting of the remote datagram address. When specified for a client
2916 process, the FAMILY, HOST, and SERVICE args are ignored.
2917
2918 The format of ADDRESS depends on the address family:
2919 - An IPv4 address is represented as an vector of integers [A B C D P]
2920 corresponding to numeric IP address A.B.C.D and port number P.
2921 - A local address is represented as a string with the address in the
2922 local address space.
2923 - An "unsupported family" address is represented by a cons (F . AV)
2924 where F is the family number and AV is a vector containing the socket
2925 address data with one element per address data byte. Do not rely on
2926 this format in portable code, as it may depend on implementation
2927 defined constants, data sizes, and data structure alignment.
2928
2929 :coding CODING -- If CODING is a symbol, it specifies the coding
2930 system used for both reading and writing for this process. If CODING
2931 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2932 ENCODING is used for writing.
2933
2934 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2935 return without waiting for the connection to complete; instead, the
2936 sentinel function will be called with second arg matching "open" (if
2937 successful) or "failed" when the connect completes. Default is to use
2938 a blocking connect (i.e. wait) for stream type connections.
2939
2940 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2941 running when Emacs is exited.
2942
2943 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2944 In the stopped state, a server process does not accept new
2945 connections, and a client process does not handle incoming traffic.
2946 The stopped state is cleared by `continue-process' and set by
2947 `stop-process'.
2948
2949 :filter FILTER -- Install FILTER as the process filter.
2950
2951 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2952 process filter are multibyte, otherwise they are unibyte.
2953 If this keyword is not specified, the strings are multibyte if
2954 `default-enable-multibyte-characters' is non-nil.
2955
2956 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2957
2958 :log LOG -- Install LOG as the server process log function. This
2959 function is called when the server accepts a network connection from a
2960 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2961 is the server process, CLIENT is the new process for the connection,
2962 and MESSAGE is a string.
2963
2964 :plist PLIST -- Install PLIST as the new process' initial plist.
2965
2966 :server QLEN -- if QLEN is non-nil, create a server process for the
2967 specified FAMILY, SERVICE, and connection type (stream or datagram).
2968 If QLEN is an integer, it is used as the max. length of the server's
2969 pending connection queue (also known as the backlog); the default
2970 queue length is 5. Default is to create a client process.
2971
2972 The following network options can be specified for this connection:
2973
2974 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2975 :dontroute BOOL -- Only send to directly connected hosts.
2976 :keepalive BOOL -- Send keep-alive messages on network stream.
2977 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2978 :oobinline BOOL -- Place out-of-band data in receive data stream.
2979 :priority INT -- Set protocol defined priority for sent packets.
2980 :reuseaddr BOOL -- Allow reusing a recently used local address
2981 (this is allowed by default for a server process).
2982 :bindtodevice NAME -- bind to interface NAME. Using this may require
2983 special privileges on some systems.
2984
2985 Consult the relevant system programmer's manual pages for more
2986 information on using these options.
2987
2988
2989 A server process will listen for and accept connections from clients.
2990 When a client connection is accepted, a new network process is created
2991 for the connection with the following parameters:
2992
2993 - The client's process name is constructed by concatenating the server
2994 process' NAME and a client identification string.
2995 - If the FILTER argument is non-nil, the client process will not get a
2996 separate process buffer; otherwise, the client's process buffer is a newly
2997 created buffer named after the server process' BUFFER name or process
2998 NAME concatenated with the client identification string.
2999 - The connection type and the process filter and sentinel parameters are
3000 inherited from the server process' TYPE, FILTER and SENTINEL.
3001 - The client process' contact info is set according to the client's
3002 addressing information (typically an IP address and a port number).
3003 - The client process' plist is initialized from the server's plist.
3004
3005 Notice that the FILTER and SENTINEL args are never used directly by
3006 the server process. Also, the BUFFER argument is not used directly by
3007 the server process, but via the optional :log function, accepted (and
3008 failed) connections may be logged in the server process' buffer.
3009
3010 The original argument list, modified with the actual connection
3011 information, is available via the `process-contact' function.
3012
3013 usage: (make-network-process &rest ARGS) */)
3014 (int nargs, Lisp_Object *args)
3015 {
3016 Lisp_Object proc;
3017 Lisp_Object contact;
3018 struct Lisp_Process *p;
3019 #ifdef HAVE_GETADDRINFO
3020 struct addrinfo ai, *res, *lres;
3021 struct addrinfo hints;
3022 const char *portstring;
3023 char portbuf[128];
3024 #else /* HAVE_GETADDRINFO */
3025 struct _emacs_addrinfo
3026 {
3027 int ai_family;
3028 int ai_socktype;
3029 int ai_protocol;
3030 int ai_addrlen;
3031 struct sockaddr *ai_addr;
3032 struct _emacs_addrinfo *ai_next;
3033 } ai, *res, *lres;
3034 #endif /* HAVE_GETADDRINFO */
3035 struct sockaddr_in address_in;
3036 #ifdef HAVE_LOCAL_SOCKETS
3037 struct sockaddr_un address_un;
3038 #endif
3039 int port;
3040 int ret = 0;
3041 int xerrno = 0;
3042 int s = -1, outch, inch;
3043 struct gcpro gcpro1;
3044 int count = SPECPDL_INDEX ();
3045 int count1;
3046 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3047 Lisp_Object tem;
3048 Lisp_Object name, buffer, host, service, address;
3049 Lisp_Object filter, sentinel;
3050 int is_non_blocking_client = 0;
3051 int is_server = 0, backlog = 5;
3052 int socktype;
3053 int family = -1;
3054
3055 if (nargs == 0)
3056 return Qnil;
3057
3058 /* Save arguments for process-contact and clone-process. */
3059 contact = Flist (nargs, args);
3060 GCPRO1 (contact);
3061
3062 #ifdef WINDOWSNT
3063 /* Ensure socket support is loaded if available. */
3064 init_winsock (TRUE);
3065 #endif
3066
3067 /* :type TYPE (nil: stream, datagram */
3068 tem = Fplist_get (contact, QCtype);
3069 if (NILP (tem))
3070 socktype = SOCK_STREAM;
3071 #ifdef DATAGRAM_SOCKETS
3072 else if (EQ (tem, Qdatagram))
3073 socktype = SOCK_DGRAM;
3074 #endif
3075 #ifdef HAVE_SEQPACKET
3076 else if (EQ (tem, Qseqpacket))
3077 socktype = SOCK_SEQPACKET;
3078 #endif
3079 else
3080 error ("Unsupported connection type");
3081
3082 /* :server BOOL */
3083 tem = Fplist_get (contact, QCserver);
3084 if (!NILP (tem))
3085 {
3086 /* Don't support network sockets when non-blocking mode is
3087 not available, since a blocked Emacs is not useful. */
3088 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3089 error ("Network servers not supported");
3090 #else
3091 is_server = 1;
3092 if (INTEGERP (tem))
3093 backlog = XINT (tem);
3094 #endif
3095 }
3096
3097 /* Make QCaddress an alias for :local (server) or :remote (client). */
3098 QCaddress = is_server ? QClocal : QCremote;
3099
3100 /* :nowait BOOL */
3101 if (!is_server && socktype != SOCK_DGRAM
3102 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3103 {
3104 #ifndef NON_BLOCKING_CONNECT
3105 error ("Non-blocking connect not supported");
3106 #else
3107 is_non_blocking_client = 1;
3108 #endif
3109 }
3110
3111 name = Fplist_get (contact, QCname);
3112 buffer = Fplist_get (contact, QCbuffer);
3113 filter = Fplist_get (contact, QCfilter);
3114 sentinel = Fplist_get (contact, QCsentinel);
3115
3116 CHECK_STRING (name);
3117
3118 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3119 ai.ai_socktype = socktype;
3120 ai.ai_protocol = 0;
3121 ai.ai_next = NULL;
3122 res = &ai;
3123
3124 /* :local ADDRESS or :remote ADDRESS */
3125 address = Fplist_get (contact, QCaddress);
3126 if (!NILP (address))
3127 {
3128 host = service = Qnil;
3129
3130 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3131 error ("Malformed :address");
3132 ai.ai_family = family;
3133 ai.ai_addr = alloca (ai.ai_addrlen);
3134 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3135 goto open_socket;
3136 }
3137
3138 /* :family FAMILY -- nil (for Inet), local, or integer. */
3139 tem = Fplist_get (contact, QCfamily);
3140 if (NILP (tem))
3141 {
3142 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3143 family = AF_UNSPEC;
3144 #else
3145 family = AF_INET;
3146 #endif
3147 }
3148 #ifdef HAVE_LOCAL_SOCKETS
3149 else if (EQ (tem, Qlocal))
3150 family = AF_LOCAL;
3151 #endif
3152 #ifdef AF_INET6
3153 else if (EQ (tem, Qipv6))
3154 family = AF_INET6;
3155 #endif
3156 else if (EQ (tem, Qipv4))
3157 family = AF_INET;
3158 else if (INTEGERP (tem))
3159 family = XINT (tem);
3160 else
3161 error ("Unknown address family");
3162
3163 ai.ai_family = family;
3164
3165 /* :service SERVICE -- string, integer (port number), or t (random port). */
3166 service = Fplist_get (contact, QCservice);
3167
3168 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3169 host = Fplist_get (contact, QChost);
3170 if (!NILP (host))
3171 {
3172 if (EQ (host, Qlocal))
3173 /* Depending on setup, "localhost" may map to different IPv4 and/or
3174 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3175 host = build_string ("127.0.0.1");
3176 CHECK_STRING (host);
3177 }
3178
3179 #ifdef HAVE_LOCAL_SOCKETS
3180 if (family == AF_LOCAL)
3181 {
3182 if (!NILP (host))
3183 {
3184 message (":family local ignores the :host \"%s\" property",
3185 SDATA (host));
3186 contact = Fplist_put (contact, QChost, Qnil);
3187 host = Qnil;
3188 }
3189 CHECK_STRING (service);
3190 memset (&address_un, 0, sizeof address_un);
3191 address_un.sun_family = AF_LOCAL;
3192 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3193 ai.ai_addr = (struct sockaddr *) &address_un;
3194 ai.ai_addrlen = sizeof address_un;
3195 goto open_socket;
3196 }
3197 #endif
3198
3199 /* Slow down polling to every ten seconds.
3200 Some kernels have a bug which causes retrying connect to fail
3201 after a connect. Polling can interfere with gethostbyname too. */
3202 #ifdef POLL_FOR_INPUT
3203 if (socktype != SOCK_DGRAM)
3204 {
3205 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3206 bind_polling_period (10);
3207 }
3208 #endif
3209
3210 #ifdef HAVE_GETADDRINFO
3211 /* If we have a host, use getaddrinfo to resolve both host and service.
3212 Otherwise, use getservbyname to lookup the service. */
3213 if (!NILP (host))
3214 {
3215
3216 /* SERVICE can either be a string or int.
3217 Convert to a C string for later use by getaddrinfo. */
3218 if (EQ (service, Qt))
3219 portstring = "0";
3220 else if (INTEGERP (service))
3221 {
3222 sprintf (portbuf, "%ld", (long) XINT (service));
3223 portstring = portbuf;
3224 }
3225 else
3226 {
3227 CHECK_STRING (service);
3228 portstring = SDATA (service);
3229 }
3230
3231 immediate_quit = 1;
3232 QUIT;
3233 memset (&hints, 0, sizeof (hints));
3234 hints.ai_flags = 0;
3235 hints.ai_family = family;
3236 hints.ai_socktype = socktype;
3237 hints.ai_protocol = 0;
3238
3239 #ifdef HAVE_RES_INIT
3240 res_init ();
3241 #endif
3242
3243 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3244 if (ret)
3245 #ifdef HAVE_GAI_STRERROR
3246 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3247 #else
3248 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3249 #endif
3250 immediate_quit = 0;
3251
3252 goto open_socket;
3253 }
3254 #endif /* HAVE_GETADDRINFO */
3255
3256 /* We end up here if getaddrinfo is not defined, or in case no hostname
3257 has been specified (e.g. for a local server process). */
3258
3259 if (EQ (service, Qt))
3260 port = 0;
3261 else if (INTEGERP (service))
3262 port = htons ((unsigned short) XINT (service));
3263 else
3264 {
3265 struct servent *svc_info;
3266 CHECK_STRING (service);
3267 svc_info = getservbyname (SDATA (service),
3268 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3269 if (svc_info == 0)
3270 error ("Unknown service: %s", SDATA (service));
3271 port = svc_info->s_port;
3272 }
3273
3274 memset (&address_in, 0, sizeof address_in);
3275 address_in.sin_family = family;
3276 address_in.sin_addr.s_addr = INADDR_ANY;
3277 address_in.sin_port = port;
3278
3279 #ifndef HAVE_GETADDRINFO
3280 if (!NILP (host))
3281 {
3282 struct hostent *host_info_ptr;
3283
3284 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3285 as it may `hang' Emacs for a very long time. */
3286 immediate_quit = 1;
3287 QUIT;
3288
3289 #ifdef HAVE_RES_INIT
3290 res_init ();
3291 #endif
3292
3293 host_info_ptr = gethostbyname (SDATA (host));
3294 immediate_quit = 0;
3295
3296 if (host_info_ptr)
3297 {
3298 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3299 host_info_ptr->h_length);
3300 family = host_info_ptr->h_addrtype;
3301 address_in.sin_family = family;
3302 }
3303 else
3304 /* Attempt to interpret host as numeric inet address */
3305 {
3306 unsigned long numeric_addr;
3307 numeric_addr = inet_addr ((char *) SDATA (host));
3308 if (numeric_addr == -1)
3309 error ("Unknown host \"%s\"", SDATA (host));
3310
3311 memcpy (&address_in.sin_addr, &numeric_addr,
3312 sizeof (address_in.sin_addr));
3313 }
3314
3315 }
3316 #endif /* not HAVE_GETADDRINFO */
3317
3318 ai.ai_family = family;
3319 ai.ai_addr = (struct sockaddr *) &address_in;
3320 ai.ai_addrlen = sizeof address_in;
3321
3322 open_socket:
3323
3324 /* Do this in case we never enter the for-loop below. */
3325 count1 = SPECPDL_INDEX ();
3326 s = -1;
3327
3328 for (lres = res; lres; lres = lres->ai_next)
3329 {
3330 int optn, optbits;
3331
3332 retry_connect:
3333
3334 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3335 if (s < 0)
3336 {
3337 xerrno = errno;
3338 continue;
3339 }
3340
3341 #ifdef DATAGRAM_SOCKETS
3342 if (!is_server && socktype == SOCK_DGRAM)
3343 break;
3344 #endif /* DATAGRAM_SOCKETS */
3345
3346 #ifdef NON_BLOCKING_CONNECT
3347 if (is_non_blocking_client)
3348 {
3349 #ifdef O_NONBLOCK
3350 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3351 #else
3352 ret = fcntl (s, F_SETFL, O_NDELAY);
3353 #endif
3354 if (ret < 0)
3355 {
3356 xerrno = errno;
3357 emacs_close (s);
3358 s = -1;
3359 continue;
3360 }
3361 }
3362 #endif
3363
3364 /* Make us close S if quit. */
3365 record_unwind_protect (close_file_unwind, make_number (s));
3366
3367 /* Parse network options in the arg list.
3368 We simply ignore anything which isn't a known option (including other keywords).
3369 An error is signaled if setting a known option fails. */
3370 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3371 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3372
3373 if (is_server)
3374 {
3375 /* Configure as a server socket. */
3376
3377 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3378 explicit :reuseaddr key to override this. */
3379 #ifdef HAVE_LOCAL_SOCKETS
3380 if (family != AF_LOCAL)
3381 #endif
3382 if (!(optbits & (1 << OPIX_REUSEADDR)))
3383 {
3384 int optval = 1;
3385 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3386 report_file_error ("Cannot set reuse option on server socket", Qnil);
3387 }
3388
3389 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3390 report_file_error ("Cannot bind server socket", Qnil);
3391
3392 #ifdef HAVE_GETSOCKNAME
3393 if (EQ (service, Qt))
3394 {
3395 struct sockaddr_in sa1;
3396 int len1 = sizeof (sa1);
3397 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3398 {
3399 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3400 service = make_number (ntohs (sa1.sin_port));
3401 contact = Fplist_put (contact, QCservice, service);
3402 }
3403 }
3404 #endif
3405
3406 if (socktype != SOCK_DGRAM && listen (s, backlog))
3407 report_file_error ("Cannot listen on server socket", Qnil);
3408
3409 break;
3410 }
3411
3412 immediate_quit = 1;
3413 QUIT;
3414
3415 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3416 xerrno = errno;
3417
3418 if (ret == 0 || xerrno == EISCONN)
3419 {
3420 /* The unwind-protect will be discarded afterwards.
3421 Likewise for immediate_quit. */
3422 break;
3423 }
3424
3425 #ifdef NON_BLOCKING_CONNECT
3426 #ifdef EINPROGRESS
3427 if (is_non_blocking_client && xerrno == EINPROGRESS)
3428 break;
3429 #else
3430 #ifdef EWOULDBLOCK
3431 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3432 break;
3433 #endif
3434 #endif
3435 #endif
3436
3437 #ifndef WINDOWSNT
3438 if (xerrno == EINTR)
3439 {
3440 /* Unlike most other syscalls connect() cannot be called
3441 again. (That would return EALREADY.) The proper way to
3442 wait for completion is select(). */
3443 int sc, len;
3444 SELECT_TYPE fdset;
3445 retry_select:
3446 FD_ZERO (&fdset);
3447 FD_SET (s, &fdset);
3448 QUIT;
3449 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3450 (EMACS_TIME *)0);
3451 if (sc == -1)
3452 {
3453 if (errno == EINTR)
3454 goto retry_select;
3455 else
3456 report_file_error ("select failed", Qnil);
3457 }
3458 eassert (sc > 0);
3459
3460 len = sizeof xerrno;
3461 eassert (FD_ISSET (s, &fdset));
3462 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3463 report_file_error ("getsockopt failed", Qnil);
3464 if (xerrno)
3465 errno = xerrno, report_file_error ("error during connect", Qnil);
3466 else
3467 break;
3468 }
3469 #endif /* !WINDOWSNT */
3470
3471 immediate_quit = 0;
3472
3473 /* Discard the unwind protect closing S. */
3474 specpdl_ptr = specpdl + count1;
3475 emacs_close (s);
3476 s = -1;
3477
3478 #ifdef WINDOWSNT
3479 if (xerrno == EINTR)
3480 goto retry_connect;
3481 #endif
3482 }
3483
3484 if (s >= 0)
3485 {
3486 #ifdef DATAGRAM_SOCKETS
3487 if (socktype == SOCK_DGRAM)
3488 {
3489 if (datagram_address[s].sa)
3490 abort ();
3491 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3492 datagram_address[s].len = lres->ai_addrlen;
3493 if (is_server)
3494 {
3495 Lisp_Object remote;
3496 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3497 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3498 {
3499 int rfamily, rlen;
3500 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3501 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3502 conv_lisp_to_sockaddr (rfamily, remote,
3503 datagram_address[s].sa, rlen);
3504 }
3505 }
3506 else
3507 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3508 }
3509 #endif
3510 contact = Fplist_put (contact, QCaddress,
3511 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3512 #ifdef HAVE_GETSOCKNAME
3513 if (!is_server)
3514 {
3515 struct sockaddr_in sa1;
3516 int len1 = sizeof (sa1);
3517 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3518 contact = Fplist_put (contact, QClocal,
3519 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3520 }
3521 #endif
3522 }
3523
3524 immediate_quit = 0;
3525
3526 #ifdef HAVE_GETADDRINFO
3527 if (res != &ai)
3528 {
3529 BLOCK_INPUT;
3530 freeaddrinfo (res);
3531 UNBLOCK_INPUT;
3532 }
3533 #endif
3534
3535 /* Discard the unwind protect for closing S, if any. */
3536 specpdl_ptr = specpdl + count1;
3537
3538 /* Unwind bind_polling_period and request_sigio. */
3539 unbind_to (count, Qnil);
3540
3541 if (s < 0)
3542 {
3543 /* If non-blocking got this far - and failed - assume non-blocking is
3544 not supported after all. This is probably a wrong assumption, but
3545 the normal blocking calls to open-network-stream handles this error
3546 better. */
3547 if (is_non_blocking_client)
3548 return Qnil;
3549
3550 errno = xerrno;
3551 if (is_server)
3552 report_file_error ("make server process failed", contact);
3553 else
3554 report_file_error ("make client process failed", contact);
3555 }
3556
3557 inch = s;
3558 outch = s;
3559
3560 if (!NILP (buffer))
3561 buffer = Fget_buffer_create (buffer);
3562 proc = make_process (name);
3563
3564 chan_process[inch] = proc;
3565
3566 #ifdef O_NONBLOCK
3567 fcntl (inch, F_SETFL, O_NONBLOCK);
3568 #else
3569 #ifdef O_NDELAY
3570 fcntl (inch, F_SETFL, O_NDELAY);
3571 #endif
3572 #endif
3573
3574 p = XPROCESS (proc);
3575
3576 p->childp = contact;
3577 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3578 p->type = Qnetwork;
3579
3580 p->buffer = buffer;
3581 p->sentinel = sentinel;
3582 p->filter = filter;
3583 p->log = Fplist_get (contact, QClog);
3584 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3585 p->kill_without_query = 1;
3586 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3587 p->command = Qt;
3588 p->pid = 0;
3589 p->infd = inch;
3590 p->outfd = outch;
3591 if (is_server && socktype != SOCK_DGRAM)
3592 p->status = Qlisten;
3593
3594 /* Make the process marker point into the process buffer (if any). */
3595 if (BUFFERP (buffer))
3596 set_marker_both (p->mark, buffer,
3597 BUF_ZV (XBUFFER (buffer)),
3598 BUF_ZV_BYTE (XBUFFER (buffer)));
3599
3600 #ifdef NON_BLOCKING_CONNECT
3601 if (is_non_blocking_client)
3602 {
3603 /* We may get here if connect did succeed immediately. However,
3604 in that case, we still need to signal this like a non-blocking
3605 connection. */
3606 p->status = Qconnect;
3607 if (!FD_ISSET (inch, &connect_wait_mask))
3608 {
3609 FD_SET (inch, &connect_wait_mask);
3610 num_pending_connects++;
3611 }
3612 }
3613 else
3614 #endif
3615 /* A server may have a client filter setting of Qt, but it must
3616 still listen for incoming connects unless it is stopped. */
3617 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3618 || (EQ (p->status, Qlisten) && NILP (p->command)))
3619 {
3620 FD_SET (inch, &input_wait_mask);
3621 FD_SET (inch, &non_keyboard_wait_mask);
3622 }
3623
3624 if (inch > max_process_desc)
3625 max_process_desc = inch;
3626
3627 tem = Fplist_member (contact, QCcoding);
3628 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3629 tem = Qnil; /* No error message (too late!). */
3630
3631 {
3632 /* Setup coding systems for communicating with the network stream. */
3633 struct gcpro gcpro1;
3634 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3635 Lisp_Object coding_systems = Qt;
3636 Lisp_Object args[5], val;
3637
3638 if (!NILP (tem))
3639 {
3640 val = XCAR (XCDR (tem));
3641 if (CONSP (val))
3642 val = XCAR (val);
3643 }
3644 else if (!NILP (Vcoding_system_for_read))
3645 val = Vcoding_system_for_read;
3646 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3647 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3648 /* We dare not decode end-of-line format by setting VAL to
3649 Qraw_text, because the existing Emacs Lisp libraries
3650 assume that they receive bare code including a sequene of
3651 CR LF. */
3652 val = Qnil;
3653 else
3654 {
3655 if (NILP (host) || NILP (service))
3656 coding_systems = Qnil;
3657 else
3658 {
3659 args[0] = Qopen_network_stream, args[1] = name,
3660 args[2] = buffer, args[3] = host, args[4] = service;
3661 GCPRO1 (proc);
3662 coding_systems = Ffind_operation_coding_system (5, args);
3663 UNGCPRO;
3664 }
3665 if (CONSP (coding_systems))
3666 val = XCAR (coding_systems);
3667 else if (CONSP (Vdefault_process_coding_system))
3668 val = XCAR (Vdefault_process_coding_system);
3669 else
3670 val = Qnil;
3671 }
3672 p->decode_coding_system = val;
3673
3674 if (!NILP (tem))
3675 {
3676 val = XCAR (XCDR (tem));
3677 if (CONSP (val))
3678 val = XCDR (val);
3679 }
3680 else if (!NILP (Vcoding_system_for_write))
3681 val = Vcoding_system_for_write;
3682 else if (NILP (current_buffer->enable_multibyte_characters))
3683 val = Qnil;
3684 else
3685 {
3686 if (EQ (coding_systems, Qt))
3687 {
3688 if (NILP (host) || NILP (service))
3689 coding_systems = Qnil;
3690 else
3691 {
3692 args[0] = Qopen_network_stream, args[1] = name,
3693 args[2] = buffer, args[3] = host, args[4] = service;
3694 GCPRO1 (proc);
3695 coding_systems = Ffind_operation_coding_system (5, args);
3696 UNGCPRO;
3697 }
3698 }
3699 if (CONSP (coding_systems))
3700 val = XCDR (coding_systems);
3701 else if (CONSP (Vdefault_process_coding_system))
3702 val = XCDR (Vdefault_process_coding_system);
3703 else
3704 val = Qnil;
3705 }
3706 p->encode_coding_system = val;
3707 }
3708 setup_process_coding_systems (proc);
3709
3710 p->decoding_buf = make_uninit_string (0);
3711 p->decoding_carryover = 0;
3712 p->encoding_buf = make_uninit_string (0);
3713
3714 p->inherit_coding_system_flag
3715 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3716
3717 UNGCPRO;
3718 return proc;
3719 }
3720
3721 \f
3722 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3723
3724 #ifdef SIOCGIFCONF
3725 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3726 doc: /* Return an alist of all network interfaces and their network address.
3727 Each element is a cons, the car of which is a string containing the
3728 interface name, and the cdr is the network address in internal
3729 format; see the description of ADDRESS in `make-network-process'. */)
3730 (void)
3731 {
3732 struct ifconf ifconf;
3733 struct ifreq *ifreqs = NULL;
3734 int ifaces = 0;
3735 int buf_size, s;
3736 Lisp_Object res;
3737
3738 s = socket (AF_INET, SOCK_STREAM, 0);
3739 if (s < 0)
3740 return Qnil;
3741
3742 again:
3743 ifaces += 25;
3744 buf_size = ifaces * sizeof (ifreqs[0]);
3745 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3746 if (!ifreqs)
3747 {
3748 close (s);
3749 return Qnil;
3750 }
3751
3752 ifconf.ifc_len = buf_size;
3753 ifconf.ifc_req = ifreqs;
3754 if (ioctl (s, SIOCGIFCONF, &ifconf))
3755 {
3756 close (s);
3757 return Qnil;
3758 }
3759
3760 if (ifconf.ifc_len == buf_size)
3761 goto again;
3762
3763 close (s);
3764 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3765
3766 res = Qnil;
3767 while (--ifaces >= 0)
3768 {
3769 struct ifreq *ifq = &ifreqs[ifaces];
3770 char namebuf[sizeof (ifq->ifr_name) + 1];
3771 if (ifq->ifr_addr.sa_family != AF_INET)
3772 continue;
3773 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3774 namebuf[sizeof (ifq->ifr_name)] = 0;
3775 res = Fcons (Fcons (build_string (namebuf),
3776 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3777 sizeof (struct sockaddr))),
3778 res);
3779 }
3780
3781 return res;
3782 }
3783 #endif /* SIOCGIFCONF */
3784
3785 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3786
3787 struct ifflag_def {
3788 int flag_bit;
3789 const char *flag_sym;
3790 };
3791
3792 static const struct ifflag_def ifflag_table[] = {
3793 #ifdef IFF_UP
3794 { IFF_UP, "up" },
3795 #endif
3796 #ifdef IFF_BROADCAST
3797 { IFF_BROADCAST, "broadcast" },
3798 #endif
3799 #ifdef IFF_DEBUG
3800 { IFF_DEBUG, "debug" },
3801 #endif
3802 #ifdef IFF_LOOPBACK
3803 { IFF_LOOPBACK, "loopback" },
3804 #endif
3805 #ifdef IFF_POINTOPOINT
3806 { IFF_POINTOPOINT, "pointopoint" },
3807 #endif
3808 #ifdef IFF_RUNNING
3809 { IFF_RUNNING, "running" },
3810 #endif
3811 #ifdef IFF_NOARP
3812 { IFF_NOARP, "noarp" },
3813 #endif
3814 #ifdef IFF_PROMISC
3815 { IFF_PROMISC, "promisc" },
3816 #endif
3817 #ifdef IFF_NOTRAILERS
3818 { IFF_NOTRAILERS, "notrailers" },
3819 #endif
3820 #ifdef IFF_ALLMULTI
3821 { IFF_ALLMULTI, "allmulti" },
3822 #endif
3823 #ifdef IFF_MASTER
3824 { IFF_MASTER, "master" },
3825 #endif
3826 #ifdef IFF_SLAVE
3827 { IFF_SLAVE, "slave" },
3828 #endif
3829 #ifdef IFF_MULTICAST
3830 { IFF_MULTICAST, "multicast" },
3831 #endif
3832 #ifdef IFF_PORTSEL
3833 { IFF_PORTSEL, "portsel" },
3834 #endif
3835 #ifdef IFF_AUTOMEDIA
3836 { IFF_AUTOMEDIA, "automedia" },
3837 #endif
3838 #ifdef IFF_DYNAMIC
3839 { IFF_DYNAMIC, "dynamic" },
3840 #endif
3841 #ifdef IFF_OACTIVE
3842 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3843 #endif
3844 #ifdef IFF_SIMPLEX
3845 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3846 #endif
3847 #ifdef IFF_LINK0
3848 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3849 #endif
3850 #ifdef IFF_LINK1
3851 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3852 #endif
3853 #ifdef IFF_LINK2
3854 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3855 #endif
3856 { 0, 0 }
3857 };
3858
3859 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3860 doc: /* Return information about network interface named IFNAME.
3861 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3862 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3863 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3864 FLAGS is the current flags of the interface. */)
3865 (Lisp_Object ifname)
3866 {
3867 struct ifreq rq;
3868 Lisp_Object res = Qnil;
3869 Lisp_Object elt;
3870 int s;
3871 int any = 0;
3872
3873 CHECK_STRING (ifname);
3874
3875 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3876 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3877
3878 s = socket (AF_INET, SOCK_STREAM, 0);
3879 if (s < 0)
3880 return Qnil;
3881
3882 elt = Qnil;
3883 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3884 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3885 {
3886 int flags = rq.ifr_flags;
3887 const struct ifflag_def *fp;
3888 int fnum;
3889
3890 any++;
3891 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3892 {
3893 if (flags & fp->flag_bit)
3894 {
3895 elt = Fcons (intern (fp->flag_sym), elt);
3896 flags -= fp->flag_bit;
3897 }
3898 }
3899 for (fnum = 0; flags && fnum < 32; fnum++)
3900 {
3901 if (flags & (1 << fnum))
3902 {
3903 elt = Fcons (make_number (fnum), elt);
3904 }
3905 }
3906 }
3907 #endif
3908 res = Fcons (elt, res);
3909
3910 elt = Qnil;
3911 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3912 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3913 {
3914 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3915 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3916 int n;
3917
3918 any++;
3919 for (n = 0; n < 6; n++)
3920 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3921 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3922 }
3923 #endif
3924 res = Fcons (elt, res);
3925
3926 elt = Qnil;
3927 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3928 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3929 {
3930 any++;
3931 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3932 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3933 #else
3934 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3935 #endif
3936 }
3937 #endif
3938 res = Fcons (elt, res);
3939
3940 elt = Qnil;
3941 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3942 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3943 {
3944 any++;
3945 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3946 }
3947 #endif
3948 res = Fcons (elt, res);
3949
3950 elt = Qnil;
3951 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3952 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3953 {
3954 any++;
3955 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3956 }
3957 #endif
3958 res = Fcons (elt, res);
3959
3960 close (s);
3961
3962 return any ? res : Qnil;
3963 }
3964 #endif
3965 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
3966
3967 /* Turn off input and output for process PROC. */
3968
3969 void
3970 deactivate_process (Lisp_Object proc)
3971 {
3972 register int inchannel, outchannel;
3973 register struct Lisp_Process *p = XPROCESS (proc);
3974
3975 inchannel = p->infd;
3976 outchannel = p->outfd;
3977
3978 #ifdef ADAPTIVE_READ_BUFFERING
3979 if (p->read_output_delay > 0)
3980 {
3981 if (--process_output_delay_count < 0)
3982 process_output_delay_count = 0;
3983 p->read_output_delay = 0;
3984 p->read_output_skip = 0;
3985 }
3986 #endif
3987
3988 if (inchannel >= 0)
3989 {
3990 /* Beware SIGCHLD hereabouts. */
3991 flush_pending_output (inchannel);
3992 emacs_close (inchannel);
3993 if (outchannel >= 0 && outchannel != inchannel)
3994 emacs_close (outchannel);
3995
3996 p->infd = -1;
3997 p->outfd = -1;
3998 #ifdef DATAGRAM_SOCKETS
3999 if (DATAGRAM_CHAN_P (inchannel))
4000 {
4001 xfree (datagram_address[inchannel].sa);
4002 datagram_address[inchannel].sa = 0;
4003 datagram_address[inchannel].len = 0;
4004 }
4005 #endif
4006 chan_process[inchannel] = Qnil;
4007 FD_CLR (inchannel, &input_wait_mask);
4008 FD_CLR (inchannel, &non_keyboard_wait_mask);
4009 #ifdef NON_BLOCKING_CONNECT
4010 if (FD_ISSET (inchannel, &connect_wait_mask))
4011 {
4012 FD_CLR (inchannel, &connect_wait_mask);
4013 if (--num_pending_connects < 0)
4014 abort ();
4015 }
4016 #endif
4017 if (inchannel == max_process_desc)
4018 {
4019 int i;
4020 /* We just closed the highest-numbered process input descriptor,
4021 so recompute the highest-numbered one now. */
4022 max_process_desc = 0;
4023 for (i = 0; i < MAXDESC; i++)
4024 if (!NILP (chan_process[i]))
4025 max_process_desc = i;
4026 }
4027 }
4028 }
4029
4030 \f
4031 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4032 0, 4, 0,
4033 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4034 It is read into the process' buffers or given to their filter functions.
4035 Non-nil arg PROCESS means do not return until some output has been received
4036 from PROCESS.
4037
4038 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4039 and milliseconds to wait; return after that much time whether or not
4040 there is any subprocess output. If SECONDS is a floating point number,
4041 it specifies a fractional number of seconds to wait.
4042 The MILLISEC argument is obsolete and should be avoided.
4043
4044 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4045 from PROCESS, suspending reading output from other processes.
4046 If JUST-THIS-ONE is an integer, don't run any timers either.
4047 Return non-nil if we received any output before the timeout expired. */)
4048 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4049 {
4050 int secs, usecs = 0;
4051
4052 if (! NILP (process))
4053 CHECK_PROCESS (process);
4054 else
4055 just_this_one = Qnil;
4056
4057 if (!NILP (millisec))
4058 { /* Obsolete calling convention using integers rather than floats. */
4059 CHECK_NUMBER (millisec);
4060 if (NILP (seconds))
4061 seconds = make_float (XINT (millisec) / 1000.0);
4062 else
4063 {
4064 CHECK_NUMBER (seconds);
4065 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4066 }
4067 }
4068
4069 if (!NILP (seconds))
4070 {
4071 if (INTEGERP (seconds))
4072 secs = XINT (seconds);
4073 else if (FLOATP (seconds))
4074 {
4075 double timeout = XFLOAT_DATA (seconds);
4076 secs = (int) timeout;
4077 usecs = (int) ((timeout - (double) secs) * 1000000);
4078 }
4079 else
4080 wrong_type_argument (Qnumberp, seconds);
4081
4082 if (secs < 0 || (secs == 0 && usecs == 0))
4083 secs = -1, usecs = 0;
4084 }
4085 else
4086 secs = NILP (process) ? -1 : 0;
4087
4088 return
4089 (wait_reading_process_output (secs, usecs, 0, 0,
4090 Qnil,
4091 !NILP (process) ? XPROCESS (process) : NULL,
4092 NILP (just_this_one) ? 0 :
4093 !INTEGERP (just_this_one) ? 1 : -1)
4094 ? Qt : Qnil);
4095 }
4096
4097 /* Accept a connection for server process SERVER on CHANNEL. */
4098
4099 static int connect_counter = 0;
4100
4101 static void
4102 server_accept_connection (Lisp_Object server, int channel)
4103 {
4104 Lisp_Object proc, caller, name, buffer;
4105 Lisp_Object contact, host, service;
4106 struct Lisp_Process *ps= XPROCESS (server);
4107 struct Lisp_Process *p;
4108 int s;
4109 union u_sockaddr {
4110 struct sockaddr sa;
4111 struct sockaddr_in in;
4112 #ifdef AF_INET6
4113 struct sockaddr_in6 in6;
4114 #endif
4115 #ifdef HAVE_LOCAL_SOCKETS
4116 struct sockaddr_un un;
4117 #endif
4118 } saddr;
4119 int len = sizeof saddr;
4120
4121 s = accept (channel, &saddr.sa, &len);
4122
4123 if (s < 0)
4124 {
4125 int code = errno;
4126
4127 if (code == EAGAIN)
4128 return;
4129 #ifdef EWOULDBLOCK
4130 if (code == EWOULDBLOCK)
4131 return;
4132 #endif
4133
4134 if (!NILP (ps->log))
4135 call3 (ps->log, server, Qnil,
4136 concat3 (build_string ("accept failed with code"),
4137 Fnumber_to_string (make_number (code)),
4138 build_string ("\n")));
4139 return;
4140 }
4141
4142 connect_counter++;
4143
4144 /* Setup a new process to handle the connection. */
4145
4146 /* Generate a unique identification of the caller, and build contact
4147 information for this process. */
4148 host = Qt;
4149 service = Qnil;
4150 switch (saddr.sa.sa_family)
4151 {
4152 case AF_INET:
4153 {
4154 Lisp_Object args[5];
4155 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4156 args[0] = build_string ("%d.%d.%d.%d");
4157 args[1] = make_number (*ip++);
4158 args[2] = make_number (*ip++);
4159 args[3] = make_number (*ip++);
4160 args[4] = make_number (*ip++);
4161 host = Fformat (5, args);
4162 service = make_number (ntohs (saddr.in.sin_port));
4163
4164 args[0] = build_string (" <%s:%d>");
4165 args[1] = host;
4166 args[2] = service;
4167 caller = Fformat (3, args);
4168 }
4169 break;
4170
4171 #ifdef AF_INET6
4172 case AF_INET6:
4173 {
4174 Lisp_Object args[9];
4175 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4176 int i;
4177 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4178 for (i = 0; i < 8; i++)
4179 args[i+1] = make_number (ntohs (ip6[i]));
4180 host = Fformat (9, args);
4181 service = make_number (ntohs (saddr.in.sin_port));
4182
4183 args[0] = build_string (" <[%s]:%d>");
4184 args[1] = host;
4185 args[2] = service;
4186 caller = Fformat (3, args);
4187 }
4188 break;
4189 #endif
4190
4191 #ifdef HAVE_LOCAL_SOCKETS
4192 case AF_LOCAL:
4193 #endif
4194 default:
4195 caller = Fnumber_to_string (make_number (connect_counter));
4196 caller = concat3 (build_string (" <"), caller, build_string (">"));
4197 break;
4198 }
4199
4200 /* Create a new buffer name for this process if it doesn't have a
4201 filter. The new buffer name is based on the buffer name or
4202 process name of the server process concatenated with the caller
4203 identification. */
4204
4205 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4206 buffer = Qnil;
4207 else
4208 {
4209 buffer = ps->buffer;
4210 if (!NILP (buffer))
4211 buffer = Fbuffer_name (buffer);
4212 else
4213 buffer = ps->name;
4214 if (!NILP (buffer))
4215 {
4216 buffer = concat2 (buffer, caller);
4217 buffer = Fget_buffer_create (buffer);
4218 }
4219 }
4220
4221 /* Generate a unique name for the new server process. Combine the
4222 server process name with the caller identification. */
4223
4224 name = concat2 (ps->name, caller);
4225 proc = make_process (name);
4226
4227 chan_process[s] = proc;
4228
4229 #ifdef O_NONBLOCK
4230 fcntl (s, F_SETFL, O_NONBLOCK);
4231 #else
4232 #ifdef O_NDELAY
4233 fcntl (s, F_SETFL, O_NDELAY);
4234 #endif
4235 #endif
4236
4237 p = XPROCESS (proc);
4238
4239 /* Build new contact information for this setup. */
4240 contact = Fcopy_sequence (ps->childp);
4241 contact = Fplist_put (contact, QCserver, Qnil);
4242 contact = Fplist_put (contact, QChost, host);
4243 if (!NILP (service))
4244 contact = Fplist_put (contact, QCservice, service);
4245 contact = Fplist_put (contact, QCremote,
4246 conv_sockaddr_to_lisp (&saddr.sa, len));
4247 #ifdef HAVE_GETSOCKNAME
4248 len = sizeof saddr;
4249 if (getsockname (s, &saddr.sa, &len) == 0)
4250 contact = Fplist_put (contact, QClocal,
4251 conv_sockaddr_to_lisp (&saddr.sa, len));
4252 #endif
4253
4254 p->childp = contact;
4255 p->plist = Fcopy_sequence (ps->plist);
4256 p->type = Qnetwork;
4257
4258 p->buffer = buffer;
4259 p->sentinel = ps->sentinel;
4260 p->filter = ps->filter;
4261 p->command = Qnil;
4262 p->pid = 0;
4263 p->infd = s;
4264 p->outfd = s;
4265 p->status = Qrun;
4266
4267 /* Client processes for accepted connections are not stopped initially. */
4268 if (!EQ (p->filter, Qt))
4269 {
4270 FD_SET (s, &input_wait_mask);
4271 FD_SET (s, &non_keyboard_wait_mask);
4272 }
4273
4274 if (s > max_process_desc)
4275 max_process_desc = s;
4276
4277 /* Setup coding system for new process based on server process.
4278 This seems to be the proper thing to do, as the coding system
4279 of the new process should reflect the settings at the time the
4280 server socket was opened; not the current settings. */
4281
4282 p->decode_coding_system = ps->decode_coding_system;
4283 p->encode_coding_system = ps->encode_coding_system;
4284 setup_process_coding_systems (proc);
4285
4286 p->decoding_buf = make_uninit_string (0);
4287 p->decoding_carryover = 0;
4288 p->encoding_buf = make_uninit_string (0);
4289
4290 p->inherit_coding_system_flag
4291 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4292
4293 if (!NILP (ps->log))
4294 call3 (ps->log, server, proc,
4295 concat3 (build_string ("accept from "),
4296 (STRINGP (host) ? host : build_string ("-")),
4297 build_string ("\n")));
4298
4299 if (!NILP (p->sentinel))
4300 exec_sentinel (proc,
4301 concat3 (build_string ("open from "),
4302 (STRINGP (host) ? host : build_string ("-")),
4303 build_string ("\n")));
4304 }
4305
4306 /* This variable is different from waiting_for_input in keyboard.c.
4307 It is used to communicate to a lisp process-filter/sentinel (via the
4308 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4309 for user-input when that process-filter was called.
4310 waiting_for_input cannot be used as that is by definition 0 when
4311 lisp code is being evalled.
4312 This is also used in record_asynch_buffer_change.
4313 For that purpose, this must be 0
4314 when not inside wait_reading_process_output. */
4315 static int waiting_for_user_input_p;
4316
4317 static Lisp_Object
4318 wait_reading_process_output_unwind (Lisp_Object data)
4319 {
4320 waiting_for_user_input_p = XINT (data);
4321 return Qnil;
4322 }
4323
4324 /* This is here so breakpoints can be put on it. */
4325 static void
4326 wait_reading_process_output_1 (void)
4327 {
4328 }
4329
4330 /* Use a wrapper around select to work around a bug in gdb 5.3.
4331 Normally, the wrapper is optimized away by inlining.
4332
4333 If emacs is stopped inside select, the gdb backtrace doesn't
4334 show the function which called select, so it is practically
4335 impossible to step through wait_reading_process_output. */
4336
4337 #ifndef select
4338 static INLINE int
4339 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4340 {
4341 return select (n, rfd, wfd, xfd, tmo);
4342 }
4343 #define select select_wrapper
4344 #endif
4345
4346 /* Read and dispose of subprocess output while waiting for timeout to
4347 elapse and/or keyboard input to be available.
4348
4349 TIME_LIMIT is:
4350 timeout in seconds, or
4351 zero for no limit, or
4352 -1 means gobble data immediately available but don't wait for any.
4353
4354 MICROSECS is:
4355 an additional duration to wait, measured in microseconds.
4356 If this is nonzero and time_limit is 0, then the timeout
4357 consists of MICROSECS only.
4358
4359 READ_KBD is a lisp value:
4360 0 to ignore keyboard input, or
4361 1 to return when input is available, or
4362 -1 meaning caller will actually read the input, so don't throw to
4363 the quit handler, or
4364
4365 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4366 output that arrives.
4367
4368 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4369 (and gobble terminal input into the buffer if any arrives).
4370
4371 If WAIT_PROC is specified, wait until something arrives from that
4372 process. The return value is true if we read some input from
4373 that process.
4374
4375 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4376 (suspending output from other processes). A negative value
4377 means don't run any timers either.
4378
4379 If WAIT_PROC is specified, then the function returns true if we
4380 received input from that process before the timeout elapsed.
4381 Otherwise, return true if we received input from any process. */
4382
4383 int
4384 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4385 int do_display,
4386 Lisp_Object wait_for_cell,
4387 struct Lisp_Process *wait_proc, int just_wait_proc)
4388 {
4389 register int channel, nfds;
4390 SELECT_TYPE Available;
4391 #ifdef NON_BLOCKING_CONNECT
4392 SELECT_TYPE Connecting;
4393 int check_connect;
4394 #endif
4395 int check_delay, no_avail;
4396 int xerrno;
4397 Lisp_Object proc;
4398 EMACS_TIME timeout, end_time;
4399 int wait_channel = -1;
4400 int got_some_input = 0;
4401 int count = SPECPDL_INDEX ();
4402
4403 FD_ZERO (&Available);
4404 #ifdef NON_BLOCKING_CONNECT
4405 FD_ZERO (&Connecting);
4406 #endif
4407
4408 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4409 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4410 message ("Blocking call to accept-process-output with quit inhibited!!");
4411
4412 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4413 if (wait_proc != NULL)
4414 wait_channel = wait_proc->infd;
4415
4416 record_unwind_protect (wait_reading_process_output_unwind,
4417 make_number (waiting_for_user_input_p));
4418 waiting_for_user_input_p = read_kbd;
4419
4420 /* Since we may need to wait several times,
4421 compute the absolute time to return at. */
4422 if (time_limit || microsecs)
4423 {
4424 EMACS_GET_TIME (end_time);
4425 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4426 EMACS_ADD_TIME (end_time, end_time, timeout);
4427 }
4428
4429 while (1)
4430 {
4431 int timeout_reduced_for_timers = 0;
4432
4433 /* If calling from keyboard input, do not quit
4434 since we want to return C-g as an input character.
4435 Otherwise, do pending quit if requested. */
4436 if (read_kbd >= 0)
4437 QUIT;
4438 #ifdef SYNC_INPUT
4439 else
4440 process_pending_signals ();
4441 #endif
4442
4443 /* Exit now if the cell we're waiting for became non-nil. */
4444 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4445 break;
4446
4447 /* Compute time from now till when time limit is up */
4448 /* Exit if already run out */
4449 if (time_limit == -1)
4450 {
4451 /* -1 specified for timeout means
4452 gobble output available now
4453 but don't wait at all. */
4454
4455 EMACS_SET_SECS_USECS (timeout, 0, 0);
4456 }
4457 else if (time_limit || microsecs)
4458 {
4459 EMACS_GET_TIME (timeout);
4460 EMACS_SUB_TIME (timeout, end_time, timeout);
4461 if (EMACS_TIME_NEG_P (timeout))
4462 break;
4463 }
4464 else
4465 {
4466 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4467 }
4468
4469 /* Normally we run timers here.
4470 But not if wait_for_cell; in those cases,
4471 the wait is supposed to be short,
4472 and those callers cannot handle running arbitrary Lisp code here. */
4473 if (NILP (wait_for_cell)
4474 && just_wait_proc >= 0)
4475 {
4476 EMACS_TIME timer_delay;
4477
4478 do
4479 {
4480 int old_timers_run = timers_run;
4481 struct buffer *old_buffer = current_buffer;
4482 Lisp_Object old_window = selected_window;
4483
4484 timer_delay = timer_check (1);
4485
4486 /* If a timer has run, this might have changed buffers
4487 an alike. Make read_key_sequence aware of that. */
4488 if (timers_run != old_timers_run
4489 && (old_buffer != current_buffer
4490 || !EQ (old_window, selected_window))
4491 && waiting_for_user_input_p == -1)
4492 record_asynch_buffer_change ();
4493
4494 if (timers_run != old_timers_run && do_display)
4495 /* We must retry, since a timer may have requeued itself
4496 and that could alter the time_delay. */
4497 redisplay_preserve_echo_area (9);
4498 else
4499 break;
4500 }
4501 while (!detect_input_pending ());
4502
4503 /* If there is unread keyboard input, also return. */
4504 if (read_kbd != 0
4505 && requeued_events_pending_p ())
4506 break;
4507
4508 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4509 {
4510 EMACS_TIME difference;
4511 EMACS_SUB_TIME (difference, timer_delay, timeout);
4512 if (EMACS_TIME_NEG_P (difference))
4513 {
4514 timeout = timer_delay;
4515 timeout_reduced_for_timers = 1;
4516 }
4517 }
4518 /* If time_limit is -1, we are not going to wait at all. */
4519 else if (time_limit != -1)
4520 {
4521 /* This is so a breakpoint can be put here. */
4522 wait_reading_process_output_1 ();
4523 }
4524 }
4525
4526 /* Cause C-g and alarm signals to take immediate action,
4527 and cause input available signals to zero out timeout.
4528
4529 It is important that we do this before checking for process
4530 activity. If we get a SIGCHLD after the explicit checks for
4531 process activity, timeout is the only way we will know. */
4532 if (read_kbd < 0)
4533 set_waiting_for_input (&timeout);
4534
4535 /* If status of something has changed, and no input is
4536 available, notify the user of the change right away. After
4537 this explicit check, we'll let the SIGCHLD handler zap
4538 timeout to get our attention. */
4539 if (update_tick != process_tick)
4540 {
4541 SELECT_TYPE Atemp;
4542 #ifdef NON_BLOCKING_CONNECT
4543 SELECT_TYPE Ctemp;
4544 #endif
4545
4546 if (kbd_on_hold_p ())
4547 FD_ZERO (&Atemp);
4548 else
4549 Atemp = input_wait_mask;
4550 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4551
4552 EMACS_SET_SECS_USECS (timeout, 0, 0);
4553 if ((select (max (max (max_process_desc, max_keyboard_desc),
4554 max_gpm_desc) + 1,
4555 &Atemp,
4556 #ifdef NON_BLOCKING_CONNECT
4557 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4558 #else
4559 (SELECT_TYPE *)0,
4560 #endif
4561 (SELECT_TYPE *)0, &timeout)
4562 <= 0))
4563 {
4564 /* It's okay for us to do this and then continue with
4565 the loop, since timeout has already been zeroed out. */
4566 clear_waiting_for_input ();
4567 status_notify (NULL);
4568 if (do_display) redisplay_preserve_echo_area (13);
4569 }
4570 }
4571
4572 /* Don't wait for output from a non-running process. Just
4573 read whatever data has already been received. */
4574 if (wait_proc && wait_proc->raw_status_new)
4575 update_status (wait_proc);
4576 if (wait_proc
4577 && ! EQ (wait_proc->status, Qrun)
4578 && ! EQ (wait_proc->status, Qconnect))
4579 {
4580 int nread, total_nread = 0;
4581
4582 clear_waiting_for_input ();
4583 XSETPROCESS (proc, wait_proc);
4584
4585 /* Read data from the process, until we exhaust it. */
4586 while (wait_proc->infd >= 0)
4587 {
4588 nread = read_process_output (proc, wait_proc->infd);
4589
4590 if (nread == 0)
4591 break;
4592
4593 if (0 < nread)
4594 {
4595 total_nread += nread;
4596 got_some_input = 1;
4597 }
4598 #ifdef EIO
4599 else if (nread == -1 && EIO == errno)
4600 break;
4601 #endif
4602 #ifdef EAGAIN
4603 else if (nread == -1 && EAGAIN == errno)
4604 break;
4605 #endif
4606 #ifdef EWOULDBLOCK
4607 else if (nread == -1 && EWOULDBLOCK == errno)
4608 break;
4609 #endif
4610 }
4611 if (total_nread > 0 && do_display)
4612 redisplay_preserve_echo_area (10);
4613
4614 break;
4615 }
4616
4617 /* Wait till there is something to do */
4618
4619 if (wait_proc && just_wait_proc)
4620 {
4621 if (wait_proc->infd < 0) /* Terminated */
4622 break;
4623 FD_SET (wait_proc->infd, &Available);
4624 check_delay = 0;
4625 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4626 }
4627 else if (!NILP (wait_for_cell))
4628 {
4629 Available = non_process_wait_mask;
4630 check_delay = 0;
4631 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4632 }
4633 else
4634 {
4635 if (! read_kbd)
4636 Available = non_keyboard_wait_mask;
4637 else
4638 Available = input_wait_mask;
4639 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4640 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4641 }
4642
4643 /* If frame size has changed or the window is newly mapped,
4644 redisplay now, before we start to wait. There is a race
4645 condition here; if a SIGIO arrives between now and the select
4646 and indicates that a frame is trashed, the select may block
4647 displaying a trashed screen. */
4648 if (frame_garbaged && do_display)
4649 {
4650 clear_waiting_for_input ();
4651 redisplay_preserve_echo_area (11);
4652 if (read_kbd < 0)
4653 set_waiting_for_input (&timeout);
4654 }
4655
4656 no_avail = 0;
4657 if (read_kbd && detect_input_pending ())
4658 {
4659 nfds = 0;
4660 no_avail = 1;
4661 }
4662 else
4663 {
4664 #ifdef NON_BLOCKING_CONNECT
4665 if (check_connect)
4666 Connecting = connect_wait_mask;
4667 #endif
4668
4669 #ifdef ADAPTIVE_READ_BUFFERING
4670 /* Set the timeout for adaptive read buffering if any
4671 process has non-zero read_output_skip and non-zero
4672 read_output_delay, and we are not reading output for a
4673 specific wait_channel. It is not executed if
4674 Vprocess_adaptive_read_buffering is nil. */
4675 if (process_output_skip && check_delay > 0)
4676 {
4677 int usecs = EMACS_USECS (timeout);
4678 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4679 usecs = READ_OUTPUT_DELAY_MAX;
4680 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4681 {
4682 proc = chan_process[channel];
4683 if (NILP (proc))
4684 continue;
4685 /* Find minimum non-zero read_output_delay among the
4686 processes with non-zero read_output_skip. */
4687 if (XPROCESS (proc)->read_output_delay > 0)
4688 {
4689 check_delay--;
4690 if (!XPROCESS (proc)->read_output_skip)
4691 continue;
4692 FD_CLR (channel, &Available);
4693 XPROCESS (proc)->read_output_skip = 0;
4694 if (XPROCESS (proc)->read_output_delay < usecs)
4695 usecs = XPROCESS (proc)->read_output_delay;
4696 }
4697 }
4698 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4699 process_output_skip = 0;
4700 }
4701 #endif
4702 #if defined (USE_GTK) || defined (HAVE_GCONF)
4703 nfds = xg_select
4704 #elif defined (HAVE_NS)
4705 nfds = ns_select
4706 #else
4707 nfds = select
4708 #endif
4709 (max (max (max_process_desc, max_keyboard_desc),
4710 max_gpm_desc) + 1,
4711 &Available,
4712 #ifdef NON_BLOCKING_CONNECT
4713 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4714 #else
4715 (SELECT_TYPE *)0,
4716 #endif
4717 (SELECT_TYPE *)0, &timeout);
4718 }
4719
4720 xerrno = errno;
4721
4722 /* Make C-g and alarm signals set flags again */
4723 clear_waiting_for_input ();
4724
4725 /* If we woke up due to SIGWINCH, actually change size now. */
4726 do_pending_window_change (0);
4727
4728 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4729 /* We wanted the full specified time, so return now. */
4730 break;
4731 if (nfds < 0)
4732 {
4733 if (xerrno == EINTR)
4734 no_avail = 1;
4735 else if (xerrno == EBADF)
4736 {
4737 #ifdef AIX
4738 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4739 the child's closure of the pts gives the parent a SIGHUP, and
4740 the ptc file descriptor is automatically closed,
4741 yielding EBADF here or at select() call above.
4742 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4743 in m/ibmrt-aix.h), and here we just ignore the select error.
4744 Cleanup occurs c/o status_notify after SIGCLD. */
4745 no_avail = 1; /* Cannot depend on values returned */
4746 #else
4747 abort ();
4748 #endif
4749 }
4750 else
4751 error ("select error: %s", emacs_strerror (xerrno));
4752 }
4753
4754 if (no_avail)
4755 {
4756 FD_ZERO (&Available);
4757 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4758 }
4759
4760 #if 0 /* When polling is used, interrupt_input is 0,
4761 so get_input_pending should read the input.
4762 So this should not be needed. */
4763 /* If we are using polling for input,
4764 and we see input available, make it get read now.
4765 Otherwise it might not actually get read for a second.
4766 And on hpux, since we turn off polling in wait_reading_process_output,
4767 it might never get read at all if we don't spend much time
4768 outside of wait_reading_process_output. */
4769 if (read_kbd && interrupt_input
4770 && keyboard_bit_set (&Available)
4771 && input_polling_used ())
4772 kill (getpid (), SIGALRM);
4773 #endif
4774
4775 /* Check for keyboard input */
4776 /* If there is any, return immediately
4777 to give it higher priority than subprocesses */
4778
4779 if (read_kbd != 0)
4780 {
4781 int old_timers_run = timers_run;
4782 struct buffer *old_buffer = current_buffer;
4783 Lisp_Object old_window = selected_window;
4784 int leave = 0;
4785
4786 if (detect_input_pending_run_timers (do_display))
4787 {
4788 swallow_events (do_display);
4789 if (detect_input_pending_run_timers (do_display))
4790 leave = 1;
4791 }
4792
4793 /* If a timer has run, this might have changed buffers
4794 an alike. Make read_key_sequence aware of that. */
4795 if (timers_run != old_timers_run
4796 && waiting_for_user_input_p == -1
4797 && (old_buffer != current_buffer
4798 || !EQ (old_window, selected_window)))
4799 record_asynch_buffer_change ();
4800
4801 if (leave)
4802 break;
4803 }
4804
4805 /* If there is unread keyboard input, also return. */
4806 if (read_kbd != 0
4807 && requeued_events_pending_p ())
4808 break;
4809
4810 /* If we are not checking for keyboard input now,
4811 do process events (but don't run any timers).
4812 This is so that X events will be processed.
4813 Otherwise they may have to wait until polling takes place.
4814 That would causes delays in pasting selections, for example.
4815
4816 (We used to do this only if wait_for_cell.) */
4817 if (read_kbd == 0 && detect_input_pending ())
4818 {
4819 swallow_events (do_display);
4820 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4821 if (detect_input_pending ())
4822 break;
4823 #endif
4824 }
4825
4826 /* Exit now if the cell we're waiting for became non-nil. */
4827 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4828 break;
4829
4830 #ifdef SIGIO
4831 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4832 go read it. This can happen with X on BSD after logging out.
4833 In that case, there really is no input and no SIGIO,
4834 but select says there is input. */
4835
4836 if (read_kbd && interrupt_input
4837 && keyboard_bit_set (&Available) && ! noninteractive)
4838 kill (getpid (), SIGIO);
4839 #endif
4840
4841 if (! wait_proc)
4842 got_some_input |= nfds > 0;
4843
4844 /* If checking input just got us a size-change event from X,
4845 obey it now if we should. */
4846 if (read_kbd || ! NILP (wait_for_cell))
4847 do_pending_window_change (0);
4848
4849 /* Check for data from a process. */
4850 if (no_avail || nfds == 0)
4851 continue;
4852
4853 /* Really FIRST_PROC_DESC should be 0 on Unix,
4854 but this is safer in the short run. */
4855 for (channel = 0; channel <= max_process_desc; channel++)
4856 {
4857 if (FD_ISSET (channel, &Available)
4858 && FD_ISSET (channel, &non_keyboard_wait_mask))
4859 {
4860 int nread;
4861
4862 /* If waiting for this channel, arrange to return as
4863 soon as no more input to be processed. No more
4864 waiting. */
4865 if (wait_channel == channel)
4866 {
4867 wait_channel = -1;
4868 time_limit = -1;
4869 got_some_input = 1;
4870 }
4871 proc = chan_process[channel];
4872 if (NILP (proc))
4873 continue;
4874
4875 /* If this is a server stream socket, accept connection. */
4876 if (EQ (XPROCESS (proc)->status, Qlisten))
4877 {
4878 server_accept_connection (proc, channel);
4879 continue;
4880 }
4881
4882 /* Read data from the process, starting with our
4883 buffered-ahead character if we have one. */
4884
4885 nread = read_process_output (proc, channel);
4886 if (nread > 0)
4887 {
4888 /* Since read_process_output can run a filter,
4889 which can call accept-process-output,
4890 don't try to read from any other processes
4891 before doing the select again. */
4892 FD_ZERO (&Available);
4893
4894 if (do_display)
4895 redisplay_preserve_echo_area (12);
4896 }
4897 #ifdef EWOULDBLOCK
4898 else if (nread == -1 && errno == EWOULDBLOCK)
4899 ;
4900 #endif
4901 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4902 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4903 #ifdef O_NONBLOCK
4904 else if (nread == -1 && errno == EAGAIN)
4905 ;
4906 #else
4907 #ifdef O_NDELAY
4908 else if (nread == -1 && errno == EAGAIN)
4909 ;
4910 /* Note that we cannot distinguish between no input
4911 available now and a closed pipe.
4912 With luck, a closed pipe will be accompanied by
4913 subprocess termination and SIGCHLD. */
4914 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4915 ;
4916 #endif /* O_NDELAY */
4917 #endif /* O_NONBLOCK */
4918 #ifdef HAVE_PTYS
4919 /* On some OSs with ptys, when the process on one end of
4920 a pty exits, the other end gets an error reading with
4921 errno = EIO instead of getting an EOF (0 bytes read).
4922 Therefore, if we get an error reading and errno =
4923 EIO, just continue, because the child process has
4924 exited and should clean itself up soon (e.g. when we
4925 get a SIGCHLD).
4926
4927 However, it has been known to happen that the SIGCHLD
4928 got lost. So raise the signal again just in case.
4929 It can't hurt. */
4930 else if (nread == -1 && errno == EIO)
4931 {
4932 /* Clear the descriptor now, so we only raise the
4933 signal once. Don't do this if `process' is only
4934 a pty. */
4935 if (XPROCESS (proc)->pid != -2)
4936 {
4937 FD_CLR (channel, &input_wait_mask);
4938 FD_CLR (channel, &non_keyboard_wait_mask);
4939
4940 kill (getpid (), SIGCHLD);
4941 }
4942 }
4943 #endif /* HAVE_PTYS */
4944 /* If we can detect process termination, don't consider the process
4945 gone just because its pipe is closed. */
4946 #ifdef SIGCHLD
4947 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4948 ;
4949 #endif
4950 else
4951 {
4952 /* Preserve status of processes already terminated. */
4953 XPROCESS (proc)->tick = ++process_tick;
4954 deactivate_process (proc);
4955 if (XPROCESS (proc)->raw_status_new)
4956 update_status (XPROCESS (proc));
4957 if (EQ (XPROCESS (proc)->status, Qrun))
4958 XPROCESS (proc)->status
4959 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4960 }
4961 }
4962 #ifdef NON_BLOCKING_CONNECT
4963 if (check_connect && FD_ISSET (channel, &Connecting)
4964 && FD_ISSET (channel, &connect_wait_mask))
4965 {
4966 struct Lisp_Process *p;
4967
4968 FD_CLR (channel, &connect_wait_mask);
4969 if (--num_pending_connects < 0)
4970 abort ();
4971
4972 proc = chan_process[channel];
4973 if (NILP (proc))
4974 continue;
4975
4976 p = XPROCESS (proc);
4977
4978 #ifdef GNU_LINUX
4979 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4980 So only use it on systems where it is known to work. */
4981 {
4982 int xlen = sizeof (xerrno);
4983 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4984 xerrno = errno;
4985 }
4986 #else
4987 {
4988 struct sockaddr pname;
4989 int pnamelen = sizeof (pname);
4990
4991 /* If connection failed, getpeername will fail. */
4992 xerrno = 0;
4993 if (getpeername (channel, &pname, &pnamelen) < 0)
4994 {
4995 /* Obtain connect failure code through error slippage. */
4996 char dummy;
4997 xerrno = errno;
4998 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4999 xerrno = errno;
5000 }
5001 }
5002 #endif
5003 if (xerrno)
5004 {
5005 p->tick = ++process_tick;
5006 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5007 deactivate_process (proc);
5008 }
5009 else
5010 {
5011 p->status = Qrun;
5012 /* Execute the sentinel here. If we had relied on
5013 status_notify to do it later, it will read input
5014 from the process before calling the sentinel. */
5015 exec_sentinel (proc, build_string ("open\n"));
5016 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5017 {
5018 FD_SET (p->infd, &input_wait_mask);
5019 FD_SET (p->infd, &non_keyboard_wait_mask);
5020 }
5021 }
5022 }
5023 #endif /* NON_BLOCKING_CONNECT */
5024 } /* end for each file descriptor */
5025 } /* end while exit conditions not met */
5026
5027 unbind_to (count, Qnil);
5028
5029 /* If calling from keyboard input, do not quit
5030 since we want to return C-g as an input character.
5031 Otherwise, do pending quit if requested. */
5032 if (read_kbd >= 0)
5033 {
5034 /* Prevent input_pending from remaining set if we quit. */
5035 clear_input_pending ();
5036 QUIT;
5037 }
5038
5039 return got_some_input;
5040 }
5041 \f
5042 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5043
5044 static Lisp_Object
5045 read_process_output_call (Lisp_Object fun_and_args)
5046 {
5047 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5048 }
5049
5050 static Lisp_Object
5051 read_process_output_error_handler (Lisp_Object error)
5052 {
5053 cmd_error_internal (error, "error in process filter: ");
5054 Vinhibit_quit = Qt;
5055 update_echo_area ();
5056 Fsleep_for (make_number (2), Qnil);
5057 return Qt;
5058 }
5059
5060 /* Read pending output from the process channel,
5061 starting with our buffered-ahead character if we have one.
5062 Yield number of decoded characters read.
5063
5064 This function reads at most 4096 characters.
5065 If you want to read all available subprocess output,
5066 you must call it repeatedly until it returns zero.
5067
5068 The characters read are decoded according to PROC's coding-system
5069 for decoding. */
5070
5071 static int
5072 read_process_output (Lisp_Object proc, register int channel)
5073 {
5074 register int nbytes;
5075 char *chars;
5076 register Lisp_Object outstream;
5077 register struct Lisp_Process *p = XPROCESS (proc);
5078 register EMACS_INT opoint;
5079 struct coding_system *coding = proc_decode_coding_system[channel];
5080 int carryover = p->decoding_carryover;
5081 int readmax = 4096;
5082 int count = SPECPDL_INDEX ();
5083 Lisp_Object odeactivate;
5084
5085 chars = (char *) alloca (carryover + readmax);
5086 if (carryover)
5087 /* See the comment above. */
5088 memcpy (chars, SDATA (p->decoding_buf), carryover);
5089
5090 #ifdef DATAGRAM_SOCKETS
5091 /* We have a working select, so proc_buffered_char is always -1. */
5092 if (DATAGRAM_CHAN_P (channel))
5093 {
5094 int len = datagram_address[channel].len;
5095 nbytes = recvfrom (channel, chars + carryover, readmax,
5096 0, datagram_address[channel].sa, &len);
5097 }
5098 else
5099 #endif
5100 if (proc_buffered_char[channel] < 0)
5101 {
5102 nbytes = emacs_read (channel, chars + carryover, readmax);
5103 #ifdef ADAPTIVE_READ_BUFFERING
5104 if (nbytes > 0 && p->adaptive_read_buffering)
5105 {
5106 int delay = p->read_output_delay;
5107 if (nbytes < 256)
5108 {
5109 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5110 {
5111 if (delay == 0)
5112 process_output_delay_count++;
5113 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5114 }
5115 }
5116 else if (delay > 0 && (nbytes == readmax))
5117 {
5118 delay -= READ_OUTPUT_DELAY_INCREMENT;
5119 if (delay == 0)
5120 process_output_delay_count--;
5121 }
5122 p->read_output_delay = delay;
5123 if (delay)
5124 {
5125 p->read_output_skip = 1;
5126 process_output_skip = 1;
5127 }
5128 }
5129 #endif
5130 }
5131 else
5132 {
5133 chars[carryover] = proc_buffered_char[channel];
5134 proc_buffered_char[channel] = -1;
5135 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5136 if (nbytes < 0)
5137 nbytes = 1;
5138 else
5139 nbytes = nbytes + 1;
5140 }
5141
5142 p->decoding_carryover = 0;
5143
5144 /* At this point, NBYTES holds number of bytes just received
5145 (including the one in proc_buffered_char[channel]). */
5146 if (nbytes <= 0)
5147 {
5148 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5149 return nbytes;
5150 coding->mode |= CODING_MODE_LAST_BLOCK;
5151 }
5152
5153 /* Now set NBYTES how many bytes we must decode. */
5154 nbytes += carryover;
5155
5156 odeactivate = Vdeactivate_mark;
5157 /* There's no good reason to let process filters change the current
5158 buffer, and many callers of accept-process-output, sit-for, and
5159 friends don't expect current-buffer to be changed from under them. */
5160 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5161
5162 /* Read and dispose of the process output. */
5163 outstream = p->filter;
5164 if (!NILP (outstream))
5165 {
5166 Lisp_Object obuffer, okeymap;
5167 Lisp_Object text;
5168 int outer_running_asynch_code = running_asynch_code;
5169 int waiting = waiting_for_user_input_p;
5170
5171 /* No need to gcpro these, because all we do with them later
5172 is test them for EQness, and none of them should be a string. */
5173 XSETBUFFER (obuffer, current_buffer);
5174 okeymap = current_buffer->keymap;
5175
5176 /* We inhibit quit here instead of just catching it so that
5177 hitting ^G when a filter happens to be running won't screw
5178 it up. */
5179 specbind (Qinhibit_quit, Qt);
5180 specbind (Qlast_nonmenu_event, Qt);
5181
5182 /* In case we get recursively called,
5183 and we already saved the match data nonrecursively,
5184 save the same match data in safely recursive fashion. */
5185 if (outer_running_asynch_code)
5186 {
5187 Lisp_Object tem;
5188 /* Don't clobber the CURRENT match data, either! */
5189 tem = Fmatch_data (Qnil, Qnil, Qnil);
5190 restore_search_regs ();
5191 record_unwind_save_match_data ();
5192 Fset_match_data (tem, Qt);
5193 }
5194
5195 /* For speed, if a search happens within this code,
5196 save the match data in a special nonrecursive fashion. */
5197 running_asynch_code = 1;
5198
5199 decode_coding_c_string (coding, chars, nbytes, Qt);
5200 text = coding->dst_object;
5201 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5202 /* A new coding system might be found. */
5203 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5204 {
5205 p->decode_coding_system = Vlast_coding_system_used;
5206
5207 /* Don't call setup_coding_system for
5208 proc_decode_coding_system[channel] here. It is done in
5209 detect_coding called via decode_coding above. */
5210
5211 /* If a coding system for encoding is not yet decided, we set
5212 it as the same as coding-system for decoding.
5213
5214 But, before doing that we must check if
5215 proc_encode_coding_system[p->outfd] surely points to a
5216 valid memory because p->outfd will be changed once EOF is
5217 sent to the process. */
5218 if (NILP (p->encode_coding_system)
5219 && proc_encode_coding_system[p->outfd])
5220 {
5221 p->encode_coding_system
5222 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5223 setup_coding_system (p->encode_coding_system,
5224 proc_encode_coding_system[p->outfd]);
5225 }
5226 }
5227
5228 if (coding->carryover_bytes > 0)
5229 {
5230 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5231 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5232 memcpy (SDATA (p->decoding_buf), coding->carryover,
5233 coding->carryover_bytes);
5234 p->decoding_carryover = coding->carryover_bytes;
5235 }
5236 if (SBYTES (text) > 0)
5237 internal_condition_case_1 (read_process_output_call,
5238 Fcons (outstream,
5239 Fcons (proc, Fcons (text, Qnil))),
5240 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5241 read_process_output_error_handler);
5242
5243 /* If we saved the match data nonrecursively, restore it now. */
5244 restore_search_regs ();
5245 running_asynch_code = outer_running_asynch_code;
5246
5247 /* Restore waiting_for_user_input_p as it was
5248 when we were called, in case the filter clobbered it. */
5249 waiting_for_user_input_p = waiting;
5250
5251 #if 0 /* Call record_asynch_buffer_change unconditionally,
5252 because we might have changed minor modes or other things
5253 that affect key bindings. */
5254 if (! EQ (Fcurrent_buffer (), obuffer)
5255 || ! EQ (current_buffer->keymap, okeymap))
5256 #endif
5257 /* But do it only if the caller is actually going to read events.
5258 Otherwise there's no need to make him wake up, and it could
5259 cause trouble (for example it would make sit_for return). */
5260 if (waiting_for_user_input_p == -1)
5261 record_asynch_buffer_change ();
5262 }
5263
5264 /* If no filter, write into buffer if it isn't dead. */
5265 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5266 {
5267 Lisp_Object old_read_only;
5268 EMACS_INT old_begv, old_zv;
5269 EMACS_INT old_begv_byte, old_zv_byte;
5270 EMACS_INT before, before_byte;
5271 EMACS_INT opoint_byte;
5272 Lisp_Object text;
5273 struct buffer *b;
5274
5275 Fset_buffer (p->buffer);
5276 opoint = PT;
5277 opoint_byte = PT_BYTE;
5278 old_read_only = current_buffer->read_only;
5279 old_begv = BEGV;
5280 old_zv = ZV;
5281 old_begv_byte = BEGV_BYTE;
5282 old_zv_byte = ZV_BYTE;
5283
5284 current_buffer->read_only = Qnil;
5285
5286 /* Insert new output into buffer
5287 at the current end-of-output marker,
5288 thus preserving logical ordering of input and output. */
5289 if (XMARKER (p->mark)->buffer)
5290 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5291 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5292 ZV_BYTE));
5293 else
5294 SET_PT_BOTH (ZV, ZV_BYTE);
5295 before = PT;
5296 before_byte = PT_BYTE;
5297
5298 /* If the output marker is outside of the visible region, save
5299 the restriction and widen. */
5300 if (! (BEGV <= PT && PT <= ZV))
5301 Fwiden ();
5302
5303 decode_coding_c_string (coding, chars, nbytes, Qt);
5304 text = coding->dst_object;
5305 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5306 /* A new coding system might be found. See the comment in the
5307 similar code in the previous `if' block. */
5308 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5309 {
5310 p->decode_coding_system = Vlast_coding_system_used;
5311 if (NILP (p->encode_coding_system)
5312 && proc_encode_coding_system[p->outfd])
5313 {
5314 p->encode_coding_system
5315 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5316 setup_coding_system (p->encode_coding_system,
5317 proc_encode_coding_system[p->outfd]);
5318 }
5319 }
5320 if (coding->carryover_bytes > 0)
5321 {
5322 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5323 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5324 memcpy (SDATA (p->decoding_buf), coding->carryover,
5325 coding->carryover_bytes);
5326 p->decoding_carryover = coding->carryover_bytes;
5327 }
5328 /* Adjust the multibyteness of TEXT to that of the buffer. */
5329 if (NILP (current_buffer->enable_multibyte_characters)
5330 != ! STRING_MULTIBYTE (text))
5331 text = (STRING_MULTIBYTE (text)
5332 ? Fstring_as_unibyte (text)
5333 : Fstring_to_multibyte (text));
5334 /* Insert before markers in case we are inserting where
5335 the buffer's mark is, and the user's next command is Meta-y. */
5336 insert_from_string_before_markers (text, 0, 0,
5337 SCHARS (text), SBYTES (text), 0);
5338
5339 /* Make sure the process marker's position is valid when the
5340 process buffer is changed in the signal_after_change above.
5341 W3 is known to do that. */
5342 if (BUFFERP (p->buffer)
5343 && (b = XBUFFER (p->buffer), b != current_buffer))
5344 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5345 else
5346 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5347
5348 update_mode_lines++;
5349
5350 /* Make sure opoint and the old restrictions
5351 float ahead of any new text just as point would. */
5352 if (opoint >= before)
5353 {
5354 opoint += PT - before;
5355 opoint_byte += PT_BYTE - before_byte;
5356 }
5357 if (old_begv > before)
5358 {
5359 old_begv += PT - before;
5360 old_begv_byte += PT_BYTE - before_byte;
5361 }
5362 if (old_zv >= before)
5363 {
5364 old_zv += PT - before;
5365 old_zv_byte += PT_BYTE - before_byte;
5366 }
5367
5368 /* If the restriction isn't what it should be, set it. */
5369 if (old_begv != BEGV || old_zv != ZV)
5370 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5371
5372
5373 current_buffer->read_only = old_read_only;
5374 SET_PT_BOTH (opoint, opoint_byte);
5375 }
5376 /* Handling the process output should not deactivate the mark. */
5377 Vdeactivate_mark = odeactivate;
5378
5379 unbind_to (count, Qnil);
5380 return nbytes;
5381 }
5382 \f
5383 /* Sending data to subprocess */
5384
5385 jmp_buf send_process_frame;
5386 Lisp_Object process_sent_to;
5387
5388 SIGTYPE
5389 send_process_trap (int ignore)
5390 {
5391 SIGNAL_THREAD_CHECK (SIGPIPE);
5392 sigunblock (sigmask (SIGPIPE));
5393 longjmp (send_process_frame, 1);
5394 }
5395
5396 /* Send some data to process PROC.
5397 BUF is the beginning of the data; LEN is the number of characters.
5398 OBJECT is the Lisp object that the data comes from. If OBJECT is
5399 nil or t, it means that the data comes from C string.
5400
5401 If OBJECT is not nil, the data is encoded by PROC's coding-system
5402 for encoding before it is sent.
5403
5404 This function can evaluate Lisp code and can garbage collect. */
5405
5406 static void
5407 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5408 volatile EMACS_INT len, volatile Lisp_Object object)
5409 {
5410 /* Use volatile to protect variables from being clobbered by longjmp. */
5411 struct Lisp_Process *p = XPROCESS (proc);
5412 EMACS_INT rv;
5413 struct coding_system *coding;
5414 struct gcpro gcpro1;
5415 SIGTYPE (*volatile old_sigpipe) (int);
5416
5417 GCPRO1 (object);
5418
5419 if (p->raw_status_new)
5420 update_status (p);
5421 if (! EQ (p->status, Qrun))
5422 error ("Process %s not running", SDATA (p->name));
5423 if (p->outfd < 0)
5424 error ("Output file descriptor of %s is closed", SDATA (p->name));
5425
5426 coding = proc_encode_coding_system[p->outfd];
5427 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5428
5429 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5430 || (BUFFERP (object)
5431 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5432 || EQ (object, Qt))
5433 {
5434 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5435 /* The coding system for encoding was changed to raw-text
5436 because we sent a unibyte text previously. Now we are
5437 sending a multibyte text, thus we must encode it by the
5438 original coding system specified for the current process. */
5439 setup_coding_system (p->encode_coding_system, coding);
5440 coding->src_multibyte = 1;
5441 }
5442 else
5443 {
5444 /* For sending a unibyte text, character code conversion should
5445 not take place but EOL conversion should. So, setup raw-text
5446 or one of the subsidiary if we have not yet done it. */
5447 if (CODING_REQUIRE_ENCODING (coding))
5448 {
5449 if (CODING_REQUIRE_FLUSHING (coding))
5450 {
5451 /* But, before changing the coding, we must flush out data. */
5452 coding->mode |= CODING_MODE_LAST_BLOCK;
5453 send_process (proc, "", 0, Qt);
5454 coding->mode &= CODING_MODE_LAST_BLOCK;
5455 }
5456 setup_coding_system (raw_text_coding_system
5457 (Vlast_coding_system_used),
5458 coding);
5459 coding->src_multibyte = 0;
5460 }
5461 }
5462 coding->dst_multibyte = 0;
5463
5464 if (CODING_REQUIRE_ENCODING (coding))
5465 {
5466 coding->dst_object = Qt;
5467 if (BUFFERP (object))
5468 {
5469 EMACS_INT from_byte, from, to;
5470 EMACS_INT save_pt, save_pt_byte;
5471 struct buffer *cur = current_buffer;
5472
5473 set_buffer_internal (XBUFFER (object));
5474 save_pt = PT, save_pt_byte = PT_BYTE;
5475
5476 from_byte = PTR_BYTE_POS (buf);
5477 from = BYTE_TO_CHAR (from_byte);
5478 to = BYTE_TO_CHAR (from_byte + len);
5479 TEMP_SET_PT_BOTH (from, from_byte);
5480 encode_coding_object (coding, object, from, from_byte,
5481 to, from_byte + len, Qt);
5482 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5483 set_buffer_internal (cur);
5484 }
5485 else if (STRINGP (object))
5486 {
5487 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5488 SBYTES (object), Qt);
5489 }
5490 else
5491 {
5492 coding->dst_object = make_unibyte_string (buf, len);
5493 coding->produced = len;
5494 }
5495
5496 len = coding->produced;
5497 object = coding->dst_object;
5498 buf = SDATA (object);
5499 }
5500
5501 if (pty_max_bytes == 0)
5502 {
5503 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5504 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5505 if (pty_max_bytes < 0)
5506 pty_max_bytes = 250;
5507 #else
5508 pty_max_bytes = 250;
5509 #endif
5510 /* Deduct one, to leave space for the eof. */
5511 pty_max_bytes--;
5512 }
5513
5514 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5515 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5516 when returning with longjmp despite being declared volatile. */
5517 if (!setjmp (send_process_frame))
5518 {
5519 process_sent_to = proc;
5520 while (len > 0)
5521 {
5522 EMACS_INT this = len;
5523
5524 /* Send this batch, using one or more write calls. */
5525 while (this > 0)
5526 {
5527 int outfd = p->outfd;
5528 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5529 #ifdef DATAGRAM_SOCKETS
5530 if (DATAGRAM_CHAN_P (outfd))
5531 {
5532 rv = sendto (outfd, (char *) buf, this,
5533 0, datagram_address[outfd].sa,
5534 datagram_address[outfd].len);
5535 if (rv < 0 && errno == EMSGSIZE)
5536 {
5537 signal (SIGPIPE, old_sigpipe);
5538 report_file_error ("sending datagram",
5539 Fcons (proc, Qnil));
5540 }
5541 }
5542 else
5543 #endif
5544 {
5545 rv = emacs_write (outfd, (char *) buf, this);
5546 #ifdef ADAPTIVE_READ_BUFFERING
5547 if (p->read_output_delay > 0
5548 && p->adaptive_read_buffering == 1)
5549 {
5550 p->read_output_delay = 0;
5551 process_output_delay_count--;
5552 p->read_output_skip = 0;
5553 }
5554 #endif
5555 }
5556 signal (SIGPIPE, old_sigpipe);
5557
5558 if (rv < 0)
5559 {
5560 if (0
5561 #ifdef EWOULDBLOCK
5562 || errno == EWOULDBLOCK
5563 #endif
5564 #ifdef EAGAIN
5565 || errno == EAGAIN
5566 #endif
5567 )
5568 /* Buffer is full. Wait, accepting input;
5569 that may allow the program
5570 to finish doing output and read more. */
5571 {
5572 int offset = 0;
5573
5574 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5575 /* A gross hack to work around a bug in FreeBSD.
5576 In the following sequence, read(2) returns
5577 bogus data:
5578
5579 write(2) 1022 bytes
5580 write(2) 954 bytes, get EAGAIN
5581 read(2) 1024 bytes in process_read_output
5582 read(2) 11 bytes in process_read_output
5583
5584 That is, read(2) returns more bytes than have
5585 ever been written successfully. The 1033 bytes
5586 read are the 1022 bytes written successfully
5587 after processing (for example with CRs added if
5588 the terminal is set up that way which it is
5589 here). The same bytes will be seen again in a
5590 later read(2), without the CRs. */
5591
5592 if (errno == EAGAIN)
5593 {
5594 int flags = FWRITE;
5595 ioctl (p->outfd, TIOCFLUSH, &flags);
5596 }
5597 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5598
5599 /* Running filters might relocate buffers or strings.
5600 Arrange to relocate BUF. */
5601 if (BUFFERP (object))
5602 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5603 else if (STRINGP (object))
5604 offset = buf - SDATA (object);
5605
5606 #ifdef EMACS_HAS_USECS
5607 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5608 #else
5609 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5610 #endif
5611
5612 if (BUFFERP (object))
5613 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5614 else if (STRINGP (object))
5615 buf = offset + SDATA (object);
5616
5617 rv = 0;
5618 }
5619 else
5620 /* This is a real error. */
5621 report_file_error ("writing to process", Fcons (proc, Qnil));
5622 }
5623 buf += rv;
5624 len -= rv;
5625 this -= rv;
5626 }
5627 }
5628 }
5629 else
5630 {
5631 signal (SIGPIPE, old_sigpipe);
5632 proc = process_sent_to;
5633 p = XPROCESS (proc);
5634 p->raw_status_new = 0;
5635 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5636 p->tick = ++process_tick;
5637 deactivate_process (proc);
5638 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5639 }
5640
5641 UNGCPRO;
5642 }
5643
5644 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5645 3, 3, 0,
5646 doc: /* Send current contents of region as input to PROCESS.
5647 PROCESS may be a process, a buffer, the name of a process or buffer, or
5648 nil, indicating the current buffer's process.
5649 Called from program, takes three arguments, PROCESS, START and END.
5650 If the region is more than 500 characters long,
5651 it is sent in several bunches. This may happen even for shorter regions.
5652 Output from processes can arrive in between bunches. */)
5653 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5654 {
5655 Lisp_Object proc;
5656 EMACS_INT start1, end1;
5657
5658 proc = get_process (process);
5659 validate_region (&start, &end);
5660
5661 if (XINT (start) < GPT && XINT (end) > GPT)
5662 move_gap (XINT (start));
5663
5664 start1 = CHAR_TO_BYTE (XINT (start));
5665 end1 = CHAR_TO_BYTE (XINT (end));
5666 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5667 Fcurrent_buffer ());
5668
5669 return Qnil;
5670 }
5671
5672 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5673 2, 2, 0,
5674 doc: /* Send PROCESS the contents of STRING as input.
5675 PROCESS may be a process, a buffer, the name of a process or buffer, or
5676 nil, indicating the current buffer's process.
5677 If STRING is more than 500 characters long,
5678 it is sent in several bunches. This may happen even for shorter strings.
5679 Output from processes can arrive in between bunches. */)
5680 (Lisp_Object process, Lisp_Object string)
5681 {
5682 Lisp_Object proc;
5683 CHECK_STRING (string);
5684 proc = get_process (process);
5685 send_process (proc, SDATA (string),
5686 SBYTES (string), string);
5687 return Qnil;
5688 }
5689 \f
5690 /* Return the foreground process group for the tty/pty that
5691 the process P uses. */
5692 static int
5693 emacs_get_tty_pgrp (struct Lisp_Process *p)
5694 {
5695 int gid = -1;
5696
5697 #ifdef TIOCGPGRP
5698 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5699 {
5700 int fd;
5701 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5702 master side. Try the slave side. */
5703 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5704
5705 if (fd != -1)
5706 {
5707 ioctl (fd, TIOCGPGRP, &gid);
5708 emacs_close (fd);
5709 }
5710 }
5711 #endif /* defined (TIOCGPGRP ) */
5712
5713 return gid;
5714 }
5715
5716 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5717 Sprocess_running_child_p, 0, 1, 0,
5718 doc: /* Return t if PROCESS has given the terminal to a child.
5719 If the operating system does not make it possible to find out,
5720 return t unconditionally. */)
5721 (Lisp_Object process)
5722 {
5723 /* Initialize in case ioctl doesn't exist or gives an error,
5724 in a way that will cause returning t. */
5725 int gid;
5726 Lisp_Object proc;
5727 struct Lisp_Process *p;
5728
5729 proc = get_process (process);
5730 p = XPROCESS (proc);
5731
5732 if (!EQ (p->type, Qreal))
5733 error ("Process %s is not a subprocess",
5734 SDATA (p->name));
5735 if (p->infd < 0)
5736 error ("Process %s is not active",
5737 SDATA (p->name));
5738
5739 gid = emacs_get_tty_pgrp (p);
5740
5741 if (gid == p->pid)
5742 return Qnil;
5743 return Qt;
5744 }
5745 \f
5746 /* send a signal number SIGNO to PROCESS.
5747 If CURRENT_GROUP is t, that means send to the process group
5748 that currently owns the terminal being used to communicate with PROCESS.
5749 This is used for various commands in shell mode.
5750 If CURRENT_GROUP is lambda, that means send to the process group
5751 that currently owns the terminal, but only if it is NOT the shell itself.
5752
5753 If NOMSG is zero, insert signal-announcements into process's buffers
5754 right away.
5755
5756 If we can, we try to signal PROCESS by sending control characters
5757 down the pty. This allows us to signal inferiors who have changed
5758 their uid, for which killpg would return an EPERM error. */
5759
5760 static void
5761 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5762 int nomsg)
5763 {
5764 Lisp_Object proc;
5765 register struct Lisp_Process *p;
5766 int gid;
5767 int no_pgrp = 0;
5768
5769 proc = get_process (process);
5770 p = XPROCESS (proc);
5771
5772 if (!EQ (p->type, Qreal))
5773 error ("Process %s is not a subprocess",
5774 SDATA (p->name));
5775 if (p->infd < 0)
5776 error ("Process %s is not active",
5777 SDATA (p->name));
5778
5779 if (!p->pty_flag)
5780 current_group = Qnil;
5781
5782 /* If we are using pgrps, get a pgrp number and make it negative. */
5783 if (NILP (current_group))
5784 /* Send the signal to the shell's process group. */
5785 gid = p->pid;
5786 else
5787 {
5788 #ifdef SIGNALS_VIA_CHARACTERS
5789 /* If possible, send signals to the entire pgrp
5790 by sending an input character to it. */
5791
5792 struct termios t;
5793 cc_t *sig_char = NULL;
5794
5795 tcgetattr (p->infd, &t);
5796
5797 switch (signo)
5798 {
5799 case SIGINT:
5800 sig_char = &t.c_cc[VINTR];
5801 break;
5802
5803 case SIGQUIT:
5804 sig_char = &t.c_cc[VQUIT];
5805 break;
5806
5807 case SIGTSTP:
5808 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5809 sig_char = &t.c_cc[VSWTCH];
5810 #else
5811 sig_char = &t.c_cc[VSUSP];
5812 #endif
5813 break;
5814 }
5815
5816 if (sig_char && *sig_char != CDISABLE)
5817 {
5818 send_process (proc, sig_char, 1, Qnil);
5819 return;
5820 }
5821 /* If we can't send the signal with a character,
5822 fall through and send it another way. */
5823
5824 /* The code above may fall through if it can't
5825 handle the signal. */
5826 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5827
5828 #ifdef TIOCGPGRP
5829 /* Get the current pgrp using the tty itself, if we have that.
5830 Otherwise, use the pty to get the pgrp.
5831 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5832 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5833 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5834 His patch indicates that if TIOCGPGRP returns an error, then
5835 we should just assume that p->pid is also the process group id. */
5836
5837 gid = emacs_get_tty_pgrp (p);
5838
5839 if (gid == -1)
5840 /* If we can't get the information, assume
5841 the shell owns the tty. */
5842 gid = p->pid;
5843
5844 /* It is not clear whether anything really can set GID to -1.
5845 Perhaps on some system one of those ioctls can or could do so.
5846 Or perhaps this is vestigial. */
5847 if (gid == -1)
5848 no_pgrp = 1;
5849 #else /* ! defined (TIOCGPGRP ) */
5850 /* Can't select pgrps on this system, so we know that
5851 the child itself heads the pgrp. */
5852 gid = p->pid;
5853 #endif /* ! defined (TIOCGPGRP ) */
5854
5855 /* If current_group is lambda, and the shell owns the terminal,
5856 don't send any signal. */
5857 if (EQ (current_group, Qlambda) && gid == p->pid)
5858 return;
5859 }
5860
5861 switch (signo)
5862 {
5863 #ifdef SIGCONT
5864 case SIGCONT:
5865 p->raw_status_new = 0;
5866 p->status = Qrun;
5867 p->tick = ++process_tick;
5868 if (!nomsg)
5869 {
5870 status_notify (NULL);
5871 redisplay_preserve_echo_area (13);
5872 }
5873 break;
5874 #endif /* ! defined (SIGCONT) */
5875 case SIGINT:
5876 case SIGQUIT:
5877 case SIGKILL:
5878 flush_pending_output (p->infd);
5879 break;
5880 }
5881
5882 /* If we don't have process groups, send the signal to the immediate
5883 subprocess. That isn't really right, but it's better than any
5884 obvious alternative. */
5885 if (no_pgrp)
5886 {
5887 kill (p->pid, signo);
5888 return;
5889 }
5890
5891 /* gid may be a pid, or minus a pgrp's number */
5892 #ifdef TIOCSIGSEND
5893 if (!NILP (current_group))
5894 {
5895 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5896 EMACS_KILLPG (gid, signo);
5897 }
5898 else
5899 {
5900 gid = - p->pid;
5901 kill (gid, signo);
5902 }
5903 #else /* ! defined (TIOCSIGSEND) */
5904 EMACS_KILLPG (gid, signo);
5905 #endif /* ! defined (TIOCSIGSEND) */
5906 }
5907
5908 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5909 doc: /* Interrupt process PROCESS.
5910 PROCESS may be a process, a buffer, or the name of a process or buffer.
5911 No arg or nil means current buffer's process.
5912 Second arg CURRENT-GROUP non-nil means send signal to
5913 the current process-group of the process's controlling terminal
5914 rather than to the process's own process group.
5915 If the process is a shell, this means interrupt current subjob
5916 rather than the shell.
5917
5918 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5919 don't send the signal. */)
5920 (Lisp_Object process, Lisp_Object current_group)
5921 {
5922 process_send_signal (process, SIGINT, current_group, 0);
5923 return process;
5924 }
5925
5926 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5927 doc: /* Kill process PROCESS. May be process or name of one.
5928 See function `interrupt-process' for more details on usage. */)
5929 (Lisp_Object process, Lisp_Object current_group)
5930 {
5931 process_send_signal (process, SIGKILL, current_group, 0);
5932 return process;
5933 }
5934
5935 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5936 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5937 See function `interrupt-process' for more details on usage. */)
5938 (Lisp_Object process, Lisp_Object current_group)
5939 {
5940 process_send_signal (process, SIGQUIT, current_group, 0);
5941 return process;
5942 }
5943
5944 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5945 doc: /* Stop process PROCESS. May be process or name of one.
5946 See function `interrupt-process' for more details on usage.
5947 If PROCESS is a network or serial process, inhibit handling of incoming
5948 traffic. */)
5949 (Lisp_Object process, Lisp_Object current_group)
5950 {
5951 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5952 {
5953 struct Lisp_Process *p;
5954
5955 p = XPROCESS (process);
5956 if (NILP (p->command)
5957 && p->infd >= 0)
5958 {
5959 FD_CLR (p->infd, &input_wait_mask);
5960 FD_CLR (p->infd, &non_keyboard_wait_mask);
5961 }
5962 p->command = Qt;
5963 return process;
5964 }
5965 #ifndef SIGTSTP
5966 error ("No SIGTSTP support");
5967 #else
5968 process_send_signal (process, SIGTSTP, current_group, 0);
5969 #endif
5970 return process;
5971 }
5972
5973 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5974 doc: /* Continue process PROCESS. May be process or name of one.
5975 See function `interrupt-process' for more details on usage.
5976 If PROCESS is a network or serial process, resume handling of incoming
5977 traffic. */)
5978 (Lisp_Object process, Lisp_Object current_group)
5979 {
5980 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5981 {
5982 struct Lisp_Process *p;
5983
5984 p = XPROCESS (process);
5985 if (EQ (p->command, Qt)
5986 && p->infd >= 0
5987 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5988 {
5989 FD_SET (p->infd, &input_wait_mask);
5990 FD_SET (p->infd, &non_keyboard_wait_mask);
5991 #ifdef WINDOWSNT
5992 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5993 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5994 #else /* not WINDOWSNT */
5995 tcflush (p->infd, TCIFLUSH);
5996 #endif /* not WINDOWSNT */
5997 }
5998 p->command = Qnil;
5999 return process;
6000 }
6001 #ifdef SIGCONT
6002 process_send_signal (process, SIGCONT, current_group, 0);
6003 #else
6004 error ("No SIGCONT support");
6005 #endif
6006 return process;
6007 }
6008
6009 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6010 2, 2, "sProcess (name or number): \nnSignal code: ",
6011 doc: /* Send PROCESS the signal with code SIGCODE.
6012 PROCESS may also be a number specifying the process id of the
6013 process to signal; in this case, the process need not be a child of
6014 this Emacs.
6015 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6016 (Lisp_Object process, Lisp_Object sigcode)
6017 {
6018 pid_t pid;
6019
6020 if (INTEGERP (process))
6021 {
6022 pid = XINT (process);
6023 goto got_it;
6024 }
6025
6026 if (FLOATP (process))
6027 {
6028 pid = (pid_t) XFLOAT_DATA (process);
6029 goto got_it;
6030 }
6031
6032 if (STRINGP (process))
6033 {
6034 Lisp_Object tem;
6035 if (tem = Fget_process (process), NILP (tem))
6036 {
6037 pid = XINT (Fstring_to_number (process, make_number (10)));
6038 if (pid > 0)
6039 goto got_it;
6040 }
6041 process = tem;
6042 }
6043 else
6044 process = get_process (process);
6045
6046 if (NILP (process))
6047 return process;
6048
6049 CHECK_PROCESS (process);
6050 pid = XPROCESS (process)->pid;
6051 if (pid <= 0)
6052 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6053
6054 got_it:
6055
6056 #define parse_signal(NAME, VALUE) \
6057 else if (!xstrcasecmp (name, NAME)) \
6058 XSETINT (sigcode, VALUE)
6059
6060 if (INTEGERP (sigcode))
6061 ;
6062 else
6063 {
6064 unsigned char *name;
6065
6066 CHECK_SYMBOL (sigcode);
6067 name = SDATA (SYMBOL_NAME (sigcode));
6068
6069 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6070 name += 3;
6071
6072 if (0)
6073 ;
6074 #ifdef SIGUSR1
6075 parse_signal ("usr1", SIGUSR1);
6076 #endif
6077 #ifdef SIGUSR2
6078 parse_signal ("usr2", SIGUSR2);
6079 #endif
6080 #ifdef SIGTERM
6081 parse_signal ("term", SIGTERM);
6082 #endif
6083 #ifdef SIGHUP
6084 parse_signal ("hup", SIGHUP);
6085 #endif
6086 #ifdef SIGINT
6087 parse_signal ("int", SIGINT);
6088 #endif
6089 #ifdef SIGQUIT
6090 parse_signal ("quit", SIGQUIT);
6091 #endif
6092 #ifdef SIGILL
6093 parse_signal ("ill", SIGILL);
6094 #endif
6095 #ifdef SIGABRT
6096 parse_signal ("abrt", SIGABRT);
6097 #endif
6098 #ifdef SIGEMT
6099 parse_signal ("emt", SIGEMT);
6100 #endif
6101 #ifdef SIGKILL
6102 parse_signal ("kill", SIGKILL);
6103 #endif
6104 #ifdef SIGFPE
6105 parse_signal ("fpe", SIGFPE);
6106 #endif
6107 #ifdef SIGBUS
6108 parse_signal ("bus", SIGBUS);
6109 #endif
6110 #ifdef SIGSEGV
6111 parse_signal ("segv", SIGSEGV);
6112 #endif
6113 #ifdef SIGSYS
6114 parse_signal ("sys", SIGSYS);
6115 #endif
6116 #ifdef SIGPIPE
6117 parse_signal ("pipe", SIGPIPE);
6118 #endif
6119 #ifdef SIGALRM
6120 parse_signal ("alrm", SIGALRM);
6121 #endif
6122 #ifdef SIGURG
6123 parse_signal ("urg", SIGURG);
6124 #endif
6125 #ifdef SIGSTOP
6126 parse_signal ("stop", SIGSTOP);
6127 #endif
6128 #ifdef SIGTSTP
6129 parse_signal ("tstp", SIGTSTP);
6130 #endif
6131 #ifdef SIGCONT
6132 parse_signal ("cont", SIGCONT);
6133 #endif
6134 #ifdef SIGCHLD
6135 parse_signal ("chld", SIGCHLD);
6136 #endif
6137 #ifdef SIGTTIN
6138 parse_signal ("ttin", SIGTTIN);
6139 #endif
6140 #ifdef SIGTTOU
6141 parse_signal ("ttou", SIGTTOU);
6142 #endif
6143 #ifdef SIGIO
6144 parse_signal ("io", SIGIO);
6145 #endif
6146 #ifdef SIGXCPU
6147 parse_signal ("xcpu", SIGXCPU);
6148 #endif
6149 #ifdef SIGXFSZ
6150 parse_signal ("xfsz", SIGXFSZ);
6151 #endif
6152 #ifdef SIGVTALRM
6153 parse_signal ("vtalrm", SIGVTALRM);
6154 #endif
6155 #ifdef SIGPROF
6156 parse_signal ("prof", SIGPROF);
6157 #endif
6158 #ifdef SIGWINCH
6159 parse_signal ("winch", SIGWINCH);
6160 #endif
6161 #ifdef SIGINFO
6162 parse_signal ("info", SIGINFO);
6163 #endif
6164 else
6165 error ("Undefined signal name %s", name);
6166 }
6167
6168 #undef parse_signal
6169
6170 return make_number (kill (pid, XINT (sigcode)));
6171 }
6172
6173 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6174 doc: /* Make PROCESS see end-of-file in its input.
6175 EOF comes after any text already sent to it.
6176 PROCESS may be a process, a buffer, the name of a process or buffer, or
6177 nil, indicating the current buffer's process.
6178 If PROCESS is a network connection, or is a process communicating
6179 through a pipe (as opposed to a pty), then you cannot send any more
6180 text to PROCESS after you call this function.
6181 If PROCESS is a serial process, wait until all output written to the
6182 process has been transmitted to the serial port. */)
6183 (Lisp_Object process)
6184 {
6185 Lisp_Object proc;
6186 struct coding_system *coding;
6187
6188 if (DATAGRAM_CONN_P (process))
6189 return process;
6190
6191 proc = get_process (process);
6192 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6193
6194 /* Make sure the process is really alive. */
6195 if (XPROCESS (proc)->raw_status_new)
6196 update_status (XPROCESS (proc));
6197 if (! EQ (XPROCESS (proc)->status, Qrun))
6198 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6199
6200 if (CODING_REQUIRE_FLUSHING (coding))
6201 {
6202 coding->mode |= CODING_MODE_LAST_BLOCK;
6203 send_process (proc, "", 0, Qnil);
6204 }
6205
6206 if (XPROCESS (proc)->pty_flag)
6207 send_process (proc, "\004", 1, Qnil);
6208 else if (EQ (XPROCESS (proc)->type, Qserial))
6209 {
6210 #ifndef WINDOWSNT
6211 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6212 error ("tcdrain() failed: %s", emacs_strerror (errno));
6213 #endif /* not WINDOWSNT */
6214 /* Do nothing on Windows because writes are blocking. */
6215 }
6216 else
6217 {
6218 int old_outfd, new_outfd;
6219
6220 #ifdef HAVE_SHUTDOWN
6221 /* If this is a network connection, or socketpair is used
6222 for communication with the subprocess, call shutdown to cause EOF.
6223 (In some old system, shutdown to socketpair doesn't work.
6224 Then we just can't win.) */
6225 if (EQ (XPROCESS (proc)->type, Qnetwork)
6226 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6227 shutdown (XPROCESS (proc)->outfd, 1);
6228 /* In case of socketpair, outfd == infd, so don't close it. */
6229 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6230 emacs_close (XPROCESS (proc)->outfd);
6231 #else /* not HAVE_SHUTDOWN */
6232 emacs_close (XPROCESS (proc)->outfd);
6233 #endif /* not HAVE_SHUTDOWN */
6234 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6235 if (new_outfd < 0)
6236 abort ();
6237 old_outfd = XPROCESS (proc)->outfd;
6238
6239 if (!proc_encode_coding_system[new_outfd])
6240 proc_encode_coding_system[new_outfd]
6241 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6242 memcpy (proc_encode_coding_system[new_outfd],
6243 proc_encode_coding_system[old_outfd],
6244 sizeof (struct coding_system));
6245 memset (proc_encode_coding_system[old_outfd], 0,
6246 sizeof (struct coding_system));
6247
6248 XPROCESS (proc)->outfd = new_outfd;
6249 }
6250 return process;
6251 }
6252 \f
6253 /* On receipt of a signal that a child status has changed, loop asking
6254 about children with changed statuses until the system says there
6255 are no more.
6256
6257 All we do is change the status; we do not run sentinels or print
6258 notifications. That is saved for the next time keyboard input is
6259 done, in order to avoid timing errors.
6260
6261 ** WARNING: this can be called during garbage collection.
6262 Therefore, it must not be fooled by the presence of mark bits in
6263 Lisp objects.
6264
6265 ** USG WARNING: Although it is not obvious from the documentation
6266 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6267 signal() before executing at least one wait(), otherwise the
6268 handler will be called again, resulting in an infinite loop. The
6269 relevant portion of the documentation reads "SIGCLD signals will be
6270 queued and the signal-catching function will be continually
6271 reentered until the queue is empty". Invoking signal() causes the
6272 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6273 Inc.
6274
6275 ** Malloc WARNING: This should never call malloc either directly or
6276 indirectly; if it does, that is a bug */
6277
6278 #ifdef SIGCHLD
6279 SIGTYPE
6280 sigchld_handler (int signo)
6281 {
6282 int old_errno = errno;
6283 Lisp_Object proc;
6284 struct Lisp_Process *p;
6285
6286 SIGNAL_THREAD_CHECK (signo);
6287
6288 while (1)
6289 {
6290 pid_t pid;
6291 int w;
6292 Lisp_Object tail;
6293
6294 #ifdef WNOHANG
6295 #ifndef WUNTRACED
6296 #define WUNTRACED 0
6297 #endif /* no WUNTRACED */
6298 /* Keep trying to get a status until we get a definitive result. */
6299 do
6300 {
6301 errno = 0;
6302 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6303 }
6304 while (pid < 0 && errno == EINTR);
6305
6306 if (pid <= 0)
6307 {
6308 /* PID == 0 means no processes found, PID == -1 means a real
6309 failure. We have done all our job, so return. */
6310
6311 errno = old_errno;
6312 return;
6313 }
6314 #else
6315 pid = wait (&w);
6316 #endif /* no WNOHANG */
6317
6318 /* Find the process that signaled us, and record its status. */
6319
6320 /* The process can have been deleted by Fdelete_process. */
6321 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6322 {
6323 Lisp_Object xpid = XCAR (tail);
6324 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6325 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6326 {
6327 XSETCAR (tail, Qnil);
6328 goto sigchld_end_of_loop;
6329 }
6330 }
6331
6332 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6333 p = 0;
6334 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6335 {
6336 proc = XCDR (XCAR (tail));
6337 p = XPROCESS (proc);
6338 if (EQ (p->type, Qreal) && p->pid == pid)
6339 break;
6340 p = 0;
6341 }
6342
6343 /* Look for an asynchronous process whose pid hasn't been filled
6344 in yet. */
6345 if (p == 0)
6346 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6347 {
6348 proc = XCDR (XCAR (tail));
6349 p = XPROCESS (proc);
6350 if (p->pid == -1)
6351 break;
6352 p = 0;
6353 }
6354
6355 /* Change the status of the process that was found. */
6356 if (p != 0)
6357 {
6358 int clear_desc_flag = 0;
6359
6360 p->tick = ++process_tick;
6361 p->raw_status = w;
6362 p->raw_status_new = 1;
6363
6364 /* If process has terminated, stop waiting for its output. */
6365 if ((WIFSIGNALED (w) || WIFEXITED (w))
6366 && p->infd >= 0)
6367 clear_desc_flag = 1;
6368
6369 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6370 if (clear_desc_flag)
6371 {
6372 FD_CLR (p->infd, &input_wait_mask);
6373 FD_CLR (p->infd, &non_keyboard_wait_mask);
6374 }
6375
6376 /* Tell wait_reading_process_output that it needs to wake up and
6377 look around. */
6378 if (input_available_clear_time)
6379 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6380 }
6381
6382 /* There was no asynchronous process found for that pid: we have
6383 a synchronous process. */
6384 else
6385 {
6386 synch_process_alive = 0;
6387
6388 /* Report the status of the synchronous process. */
6389 if (WIFEXITED (w))
6390 synch_process_retcode = WRETCODE (w);
6391 else if (WIFSIGNALED (w))
6392 synch_process_termsig = WTERMSIG (w);
6393
6394 /* Tell wait_reading_process_output that it needs to wake up and
6395 look around. */
6396 if (input_available_clear_time)
6397 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6398 }
6399
6400 sigchld_end_of_loop:
6401 ;
6402
6403 /* On some systems, we must return right away.
6404 If any more processes want to signal us, we will
6405 get another signal.
6406 Otherwise (on systems that have WNOHANG), loop around
6407 to use up all the processes that have something to tell us. */
6408 #if (defined WINDOWSNT \
6409 || (defined USG && !defined GNU_LINUX \
6410 && !(defined HPUX && defined WNOHANG)))
6411 errno = old_errno;
6412 return;
6413 #endif /* USG, but not HPUX with WNOHANG */
6414 }
6415 }
6416 #endif /* SIGCHLD */
6417 \f
6418
6419 static Lisp_Object
6420 exec_sentinel_unwind (Lisp_Object data)
6421 {
6422 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6423 return Qnil;
6424 }
6425
6426 static Lisp_Object
6427 exec_sentinel_error_handler (Lisp_Object error)
6428 {
6429 cmd_error_internal (error, "error in process sentinel: ");
6430 Vinhibit_quit = Qt;
6431 update_echo_area ();
6432 Fsleep_for (make_number (2), Qnil);
6433 return Qt;
6434 }
6435
6436 static void
6437 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6438 {
6439 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6440 register struct Lisp_Process *p = XPROCESS (proc);
6441 int count = SPECPDL_INDEX ();
6442 int outer_running_asynch_code = running_asynch_code;
6443 int waiting = waiting_for_user_input_p;
6444
6445 if (inhibit_sentinels)
6446 return;
6447
6448 /* No need to gcpro these, because all we do with them later
6449 is test them for EQness, and none of them should be a string. */
6450 odeactivate = Vdeactivate_mark;
6451 XSETBUFFER (obuffer, current_buffer);
6452 okeymap = current_buffer->keymap;
6453
6454 /* There's no good reason to let sentinels change the current
6455 buffer, and many callers of accept-process-output, sit-for, and
6456 friends don't expect current-buffer to be changed from under them. */
6457 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6458
6459 sentinel = p->sentinel;
6460 if (NILP (sentinel))
6461 return;
6462
6463 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6464 assure that it gets restored no matter how the sentinel exits. */
6465 p->sentinel = Qnil;
6466 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6467 /* Inhibit quit so that random quits don't screw up a running filter. */
6468 specbind (Qinhibit_quit, Qt);
6469 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6470
6471 /* In case we get recursively called,
6472 and we already saved the match data nonrecursively,
6473 save the same match data in safely recursive fashion. */
6474 if (outer_running_asynch_code)
6475 {
6476 Lisp_Object tem;
6477 tem = Fmatch_data (Qnil, Qnil, Qnil);
6478 restore_search_regs ();
6479 record_unwind_save_match_data ();
6480 Fset_match_data (tem, Qt);
6481 }
6482
6483 /* For speed, if a search happens within this code,
6484 save the match data in a special nonrecursive fashion. */
6485 running_asynch_code = 1;
6486
6487 internal_condition_case_1 (read_process_output_call,
6488 Fcons (sentinel,
6489 Fcons (proc, Fcons (reason, Qnil))),
6490 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6491 exec_sentinel_error_handler);
6492
6493 /* If we saved the match data nonrecursively, restore it now. */
6494 restore_search_regs ();
6495 running_asynch_code = outer_running_asynch_code;
6496
6497 Vdeactivate_mark = odeactivate;
6498
6499 /* Restore waiting_for_user_input_p as it was
6500 when we were called, in case the filter clobbered it. */
6501 waiting_for_user_input_p = waiting;
6502
6503 #if 0
6504 if (! EQ (Fcurrent_buffer (), obuffer)
6505 || ! EQ (current_buffer->keymap, okeymap))
6506 #endif
6507 /* But do it only if the caller is actually going to read events.
6508 Otherwise there's no need to make him wake up, and it could
6509 cause trouble (for example it would make sit_for return). */
6510 if (waiting_for_user_input_p == -1)
6511 record_asynch_buffer_change ();
6512
6513 unbind_to (count, Qnil);
6514 }
6515
6516 /* Report all recent events of a change in process status
6517 (either run the sentinel or output a message).
6518 This is usually done while Emacs is waiting for keyboard input
6519 but can be done at other times. */
6520
6521 static void
6522 status_notify (struct Lisp_Process *deleting_process)
6523 {
6524 register Lisp_Object proc, buffer;
6525 Lisp_Object tail, msg;
6526 struct gcpro gcpro1, gcpro2;
6527
6528 tail = Qnil;
6529 msg = Qnil;
6530 /* We need to gcpro tail; if read_process_output calls a filter
6531 which deletes a process and removes the cons to which tail points
6532 from Vprocess_alist, and then causes a GC, tail is an unprotected
6533 reference. */
6534 GCPRO2 (tail, msg);
6535
6536 /* Set this now, so that if new processes are created by sentinels
6537 that we run, we get called again to handle their status changes. */
6538 update_tick = process_tick;
6539
6540 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6541 {
6542 Lisp_Object symbol;
6543 register struct Lisp_Process *p;
6544
6545 proc = Fcdr (XCAR (tail));
6546 p = XPROCESS (proc);
6547
6548 if (p->tick != p->update_tick)
6549 {
6550 p->update_tick = p->tick;
6551
6552 /* If process is still active, read any output that remains. */
6553 while (! EQ (p->filter, Qt)
6554 && ! EQ (p->status, Qconnect)
6555 && ! EQ (p->status, Qlisten)
6556 /* Network or serial process not stopped: */
6557 && ! EQ (p->command, Qt)
6558 && p->infd >= 0
6559 && p != deleting_process
6560 && read_process_output (proc, p->infd) > 0);
6561
6562 buffer = p->buffer;
6563
6564 /* Get the text to use for the message. */
6565 if (p->raw_status_new)
6566 update_status (p);
6567 msg = status_message (p);
6568
6569 /* If process is terminated, deactivate it or delete it. */
6570 symbol = p->status;
6571 if (CONSP (p->status))
6572 symbol = XCAR (p->status);
6573
6574 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6575 || EQ (symbol, Qclosed))
6576 {
6577 if (delete_exited_processes)
6578 remove_process (proc);
6579 else
6580 deactivate_process (proc);
6581 }
6582
6583 /* The actions above may have further incremented p->tick.
6584 So set p->update_tick again
6585 so that an error in the sentinel will not cause
6586 this code to be run again. */
6587 p->update_tick = p->tick;
6588 /* Now output the message suitably. */
6589 if (!NILP (p->sentinel))
6590 exec_sentinel (proc, msg);
6591 /* Don't bother with a message in the buffer
6592 when a process becomes runnable. */
6593 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6594 {
6595 Lisp_Object tem;
6596 struct buffer *old = current_buffer;
6597 EMACS_INT opoint, opoint_byte;
6598 EMACS_INT before, before_byte;
6599
6600 /* Avoid error if buffer is deleted
6601 (probably that's why the process is dead, too) */
6602 if (NILP (XBUFFER (buffer)->name))
6603 continue;
6604 Fset_buffer (buffer);
6605
6606 opoint = PT;
6607 opoint_byte = PT_BYTE;
6608 /* Insert new output into buffer
6609 at the current end-of-output marker,
6610 thus preserving logical ordering of input and output. */
6611 if (XMARKER (p->mark)->buffer)
6612 Fgoto_char (p->mark);
6613 else
6614 SET_PT_BOTH (ZV, ZV_BYTE);
6615
6616 before = PT;
6617 before_byte = PT_BYTE;
6618
6619 tem = current_buffer->read_only;
6620 current_buffer->read_only = Qnil;
6621 insert_string ("\nProcess ");
6622 Finsert (1, &p->name);
6623 insert_string (" ");
6624 Finsert (1, &msg);
6625 current_buffer->read_only = tem;
6626 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6627
6628 if (opoint >= before)
6629 SET_PT_BOTH (opoint + (PT - before),
6630 opoint_byte + (PT_BYTE - before_byte));
6631 else
6632 SET_PT_BOTH (opoint, opoint_byte);
6633
6634 set_buffer_internal (old);
6635 }
6636 }
6637 } /* end for */
6638
6639 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6640 UNGCPRO;
6641 }
6642
6643 \f
6644 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6645 Sset_process_coding_system, 1, 3, 0,
6646 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6647 DECODING will be used to decode subprocess output and ENCODING to
6648 encode subprocess input. */)
6649 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6650 {
6651 register struct Lisp_Process *p;
6652
6653 CHECK_PROCESS (process);
6654 p = XPROCESS (process);
6655 if (p->infd < 0)
6656 error ("Input file descriptor of %s closed", SDATA (p->name));
6657 if (p->outfd < 0)
6658 error ("Output file descriptor of %s closed", SDATA (p->name));
6659 Fcheck_coding_system (decoding);
6660 Fcheck_coding_system (encoding);
6661 encoding = coding_inherit_eol_type (encoding, Qnil);
6662 p->decode_coding_system = decoding;
6663 p->encode_coding_system = encoding;
6664 setup_process_coding_systems (process);
6665
6666 return Qnil;
6667 }
6668
6669 DEFUN ("process-coding-system",
6670 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6671 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6672 (register Lisp_Object process)
6673 {
6674 CHECK_PROCESS (process);
6675 return Fcons (XPROCESS (process)->decode_coding_system,
6676 XPROCESS (process)->encode_coding_system);
6677 }
6678
6679 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6680 Sset_process_filter_multibyte, 2, 2, 0,
6681 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6682 If FLAG is non-nil, the filter is given multibyte strings.
6683 If FLAG is nil, the filter is given unibyte strings. In this case,
6684 all character code conversion except for end-of-line conversion is
6685 suppressed. */)
6686 (Lisp_Object process, Lisp_Object flag)
6687 {
6688 register struct Lisp_Process *p;
6689
6690 CHECK_PROCESS (process);
6691 p = XPROCESS (process);
6692 if (NILP (flag))
6693 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6694 setup_process_coding_systems (process);
6695
6696 return Qnil;
6697 }
6698
6699 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6700 Sprocess_filter_multibyte_p, 1, 1, 0,
6701 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6702 (Lisp_Object process)
6703 {
6704 register struct Lisp_Process *p;
6705 struct coding_system *coding;
6706
6707 CHECK_PROCESS (process);
6708 p = XPROCESS (process);
6709 coding = proc_decode_coding_system[p->infd];
6710 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6711 }
6712
6713
6714 \f
6715
6716 static int add_gpm_wait_descriptor_called_flag;
6717
6718 void
6719 add_gpm_wait_descriptor (int desc)
6720 {
6721 if (! add_gpm_wait_descriptor_called_flag)
6722 FD_CLR (0, &input_wait_mask);
6723 add_gpm_wait_descriptor_called_flag = 1;
6724 FD_SET (desc, &input_wait_mask);
6725 FD_SET (desc, &gpm_wait_mask);
6726 if (desc > max_gpm_desc)
6727 max_gpm_desc = desc;
6728 }
6729
6730 void
6731 delete_gpm_wait_descriptor (int desc)
6732 {
6733 int fd;
6734 int lim = max_gpm_desc;
6735
6736 FD_CLR (desc, &input_wait_mask);
6737 FD_CLR (desc, &non_process_wait_mask);
6738
6739 if (desc == max_gpm_desc)
6740 for (fd = 0; fd < lim; fd++)
6741 if (FD_ISSET (fd, &input_wait_mask)
6742 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6743 && !FD_ISSET (fd, &non_process_wait_mask))
6744 max_gpm_desc = fd;
6745 }
6746
6747 /* Return nonzero if *MASK has a bit set
6748 that corresponds to one of the keyboard input descriptors. */
6749
6750 static int
6751 keyboard_bit_set (fd_set *mask)
6752 {
6753 int fd;
6754
6755 for (fd = 0; fd <= max_keyboard_desc; fd++)
6756 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6757 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6758 return 1;
6759
6760 return 0;
6761 }
6762
6763 #else /* not subprocesses */
6764
6765 /* Defined on msdos.c. */
6766 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6767 EMACS_TIME *);
6768
6769 /* Implementation of wait_reading_process_output, assuming that there
6770 are no subprocesses. Used only by the MS-DOS build.
6771
6772 Wait for timeout to elapse and/or keyboard input to be available.
6773
6774 time_limit is:
6775 timeout in seconds, or
6776 zero for no limit, or
6777 -1 means gobble data immediately available but don't wait for any.
6778
6779 read_kbd is a Lisp_Object:
6780 0 to ignore keyboard input, or
6781 1 to return when input is available, or
6782 -1 means caller will actually read the input, so don't throw to
6783 the quit handler.
6784
6785 see full version for other parameters. We know that wait_proc will
6786 always be NULL, since `subprocesses' isn't defined.
6787
6788 do_display != 0 means redisplay should be done to show subprocess
6789 output that arrives.
6790
6791 Return true if we received input from any process. */
6792
6793 int
6794 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6795 int do_display,
6796 Lisp_Object wait_for_cell,
6797 struct Lisp_Process *wait_proc, int just_wait_proc)
6798 {
6799 register int nfds;
6800 EMACS_TIME end_time, timeout;
6801 SELECT_TYPE waitchannels;
6802 int xerrno;
6803
6804 /* What does time_limit really mean? */
6805 if (time_limit || microsecs)
6806 {
6807 EMACS_GET_TIME (end_time);
6808 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6809 EMACS_ADD_TIME (end_time, end_time, timeout);
6810 }
6811
6812 /* Turn off periodic alarms (in case they are in use)
6813 and then turn off any other atimers,
6814 because the select emulator uses alarms. */
6815 stop_polling ();
6816 turn_on_atimers (0);
6817
6818 while (1)
6819 {
6820 int timeout_reduced_for_timers = 0;
6821
6822 /* If calling from keyboard input, do not quit
6823 since we want to return C-g as an input character.
6824 Otherwise, do pending quit if requested. */
6825 if (read_kbd >= 0)
6826 QUIT;
6827
6828 /* Exit now if the cell we're waiting for became non-nil. */
6829 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6830 break;
6831
6832 /* Compute time from now till when time limit is up */
6833 /* Exit if already run out */
6834 if (time_limit == -1)
6835 {
6836 /* -1 specified for timeout means
6837 gobble output available now
6838 but don't wait at all. */
6839
6840 EMACS_SET_SECS_USECS (timeout, 0, 0);
6841 }
6842 else if (time_limit || microsecs)
6843 {
6844 EMACS_GET_TIME (timeout);
6845 EMACS_SUB_TIME (timeout, end_time, timeout);
6846 if (EMACS_TIME_NEG_P (timeout))
6847 break;
6848 }
6849 else
6850 {
6851 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6852 }
6853
6854 /* If our caller will not immediately handle keyboard events,
6855 run timer events directly.
6856 (Callers that will immediately read keyboard events
6857 call timer_delay on their own.) */
6858 if (NILP (wait_for_cell))
6859 {
6860 EMACS_TIME timer_delay;
6861
6862 do
6863 {
6864 int old_timers_run = timers_run;
6865 timer_delay = timer_check (1);
6866 if (timers_run != old_timers_run && do_display)
6867 /* We must retry, since a timer may have requeued itself
6868 and that could alter the time delay. */
6869 redisplay_preserve_echo_area (14);
6870 else
6871 break;
6872 }
6873 while (!detect_input_pending ());
6874
6875 /* If there is unread keyboard input, also return. */
6876 if (read_kbd != 0
6877 && requeued_events_pending_p ())
6878 break;
6879
6880 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6881 {
6882 EMACS_TIME difference;
6883 EMACS_SUB_TIME (difference, timer_delay, timeout);
6884 if (EMACS_TIME_NEG_P (difference))
6885 {
6886 timeout = timer_delay;
6887 timeout_reduced_for_timers = 1;
6888 }
6889 }
6890 }
6891
6892 /* Cause C-g and alarm signals to take immediate action,
6893 and cause input available signals to zero out timeout. */
6894 if (read_kbd < 0)
6895 set_waiting_for_input (&timeout);
6896
6897 /* Wait till there is something to do. */
6898
6899 if (! read_kbd && NILP (wait_for_cell))
6900 FD_ZERO (&waitchannels);
6901 else
6902 FD_SET (0, &waitchannels);
6903
6904 /* If a frame has been newly mapped and needs updating,
6905 reprocess its display stuff. */
6906 if (frame_garbaged && do_display)
6907 {
6908 clear_waiting_for_input ();
6909 redisplay_preserve_echo_area (15);
6910 if (read_kbd < 0)
6911 set_waiting_for_input (&timeout);
6912 }
6913
6914 if (read_kbd && detect_input_pending ())
6915 {
6916 nfds = 0;
6917 FD_ZERO (&waitchannels);
6918 }
6919 else
6920 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6921 &timeout);
6922
6923 xerrno = errno;
6924
6925 /* Make C-g and alarm signals set flags again */
6926 clear_waiting_for_input ();
6927
6928 /* If we woke up due to SIGWINCH, actually change size now. */
6929 do_pending_window_change (0);
6930
6931 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6932 /* We waited the full specified time, so return now. */
6933 break;
6934
6935 if (nfds == -1)
6936 {
6937 /* If the system call was interrupted, then go around the
6938 loop again. */
6939 if (xerrno == EINTR)
6940 FD_ZERO (&waitchannels);
6941 else
6942 error ("select error: %s", emacs_strerror (xerrno));
6943 }
6944
6945 /* Check for keyboard input */
6946
6947 if (read_kbd
6948 && detect_input_pending_run_timers (do_display))
6949 {
6950 swallow_events (do_display);
6951 if (detect_input_pending_run_timers (do_display))
6952 break;
6953 }
6954
6955 /* If there is unread keyboard input, also return. */
6956 if (read_kbd
6957 && requeued_events_pending_p ())
6958 break;
6959
6960 /* If wait_for_cell. check for keyboard input
6961 but don't run any timers.
6962 ??? (It seems wrong to me to check for keyboard
6963 input at all when wait_for_cell, but the code
6964 has been this way since July 1994.
6965 Try changing this after version 19.31.) */
6966 if (! NILP (wait_for_cell)
6967 && detect_input_pending ())
6968 {
6969 swallow_events (do_display);
6970 if (detect_input_pending ())
6971 break;
6972 }
6973
6974 /* Exit now if the cell we're waiting for became non-nil. */
6975 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6976 break;
6977 }
6978
6979 start_polling ();
6980
6981 return 0;
6982 }
6983
6984 #endif /* not subprocesses */
6985
6986 /* The following functions are needed even if async subprocesses are
6987 not supported. Some of them are no-op stubs in that case. */
6988
6989 /* Add DESC to the set of keyboard input descriptors. */
6990
6991 void
6992 add_keyboard_wait_descriptor (int desc)
6993 {
6994 #ifdef subprocesses
6995 FD_SET (desc, &input_wait_mask);
6996 FD_SET (desc, &non_process_wait_mask);
6997 if (desc > max_keyboard_desc)
6998 max_keyboard_desc = desc;
6999 #endif
7000 }
7001
7002 /* From now on, do not expect DESC to give keyboard input. */
7003
7004 void
7005 delete_keyboard_wait_descriptor (int desc)
7006 {
7007 #ifdef subprocesses
7008 int fd;
7009 int lim = max_keyboard_desc;
7010
7011 FD_CLR (desc, &input_wait_mask);
7012 FD_CLR (desc, &non_process_wait_mask);
7013
7014 if (desc == max_keyboard_desc)
7015 for (fd = 0; fd < lim; fd++)
7016 if (FD_ISSET (fd, &input_wait_mask)
7017 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7018 && !FD_ISSET (fd, &gpm_wait_mask))
7019 max_keyboard_desc = fd;
7020 #endif /* subprocesses */
7021 }
7022
7023 /* Setup coding systems of PROCESS. */
7024
7025 void
7026 setup_process_coding_systems (Lisp_Object process)
7027 {
7028 #ifdef subprocesses
7029 struct Lisp_Process *p = XPROCESS (process);
7030 int inch = p->infd;
7031 int outch = p->outfd;
7032 Lisp_Object coding_system;
7033
7034 if (inch < 0 || outch < 0)
7035 return;
7036
7037 if (!proc_decode_coding_system[inch])
7038 proc_decode_coding_system[inch]
7039 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7040 coding_system = p->decode_coding_system;
7041 if (! NILP (p->filter))
7042 ;
7043 else if (BUFFERP (p->buffer))
7044 {
7045 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7046 coding_system = raw_text_coding_system (coding_system);
7047 }
7048 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7049
7050 if (!proc_encode_coding_system[outch])
7051 proc_encode_coding_system[outch]
7052 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7053 setup_coding_system (p->encode_coding_system,
7054 proc_encode_coding_system[outch]);
7055 #endif
7056 }
7057
7058 /* Close all descriptors currently in use for communication
7059 with subprocess. This is used in a newly-forked subprocess
7060 to get rid of irrelevant descriptors. */
7061
7062 void
7063 close_process_descs (void)
7064 {
7065 #ifndef DOS_NT
7066 int i;
7067 for (i = 0; i < MAXDESC; i++)
7068 {
7069 Lisp_Object process;
7070 process = chan_process[i];
7071 if (!NILP (process))
7072 {
7073 int in = XPROCESS (process)->infd;
7074 int out = XPROCESS (process)->outfd;
7075 if (in >= 0)
7076 emacs_close (in);
7077 if (out >= 0 && in != out)
7078 emacs_close (out);
7079 }
7080 }
7081 #endif
7082 }
7083
7084 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7085 doc: /* Return the (or a) process associated with BUFFER.
7086 BUFFER may be a buffer or the name of one. */)
7087 (register Lisp_Object buffer)
7088 {
7089 #ifdef subprocesses
7090 register Lisp_Object buf, tail, proc;
7091
7092 if (NILP (buffer)) return Qnil;
7093 buf = Fget_buffer (buffer);
7094 if (NILP (buf)) return Qnil;
7095
7096 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7097 {
7098 proc = Fcdr (XCAR (tail));
7099 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7100 return proc;
7101 }
7102 #endif /* subprocesses */
7103 return Qnil;
7104 }
7105
7106 DEFUN ("process-inherit-coding-system-flag",
7107 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7108 1, 1, 0,
7109 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7110 If this flag is t, `buffer-file-coding-system' of the buffer
7111 associated with PROCESS will inherit the coding system used to decode
7112 the process output. */)
7113 (register Lisp_Object process)
7114 {
7115 #ifdef subprocesses
7116 CHECK_PROCESS (process);
7117 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7118 #else
7119 /* Ignore the argument and return the value of
7120 inherit-process-coding-system. */
7121 return inherit_process_coding_system ? Qt : Qnil;
7122 #endif
7123 }
7124
7125 /* Kill all processes associated with `buffer'.
7126 If `buffer' is nil, kill all processes */
7127
7128 void
7129 kill_buffer_processes (Lisp_Object buffer)
7130 {
7131 #ifdef subprocesses
7132 Lisp_Object tail, proc;
7133
7134 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7135 {
7136 proc = XCDR (XCAR (tail));
7137 if (PROCESSP (proc)
7138 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7139 {
7140 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7141 Fdelete_process (proc);
7142 else if (XPROCESS (proc)->infd >= 0)
7143 process_send_signal (proc, SIGHUP, Qnil, 1);
7144 }
7145 }
7146 #else /* subprocesses */
7147 /* Since we have no subprocesses, this does nothing. */
7148 #endif /* subprocesses */
7149 }
7150
7151 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7152 0, 0, 0,
7153 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7154 This is intended for use by asynchronous process output filters and sentinels. */)
7155 (void)
7156 {
7157 #ifdef subprocesses
7158 return (waiting_for_user_input_p ? Qt : Qnil);
7159 #else
7160 return Qnil;
7161 #endif
7162 }
7163
7164 /* Stop reading input from keyboard sources. */
7165
7166 void
7167 hold_keyboard_input (void)
7168 {
7169 kbd_is_on_hold = 1;
7170 }
7171
7172 /* Resume reading input from keyboard sources. */
7173
7174 void
7175 unhold_keyboard_input (void)
7176 {
7177 kbd_is_on_hold = 0;
7178 }
7179
7180 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7181
7182 int
7183 kbd_on_hold_p (void)
7184 {
7185 return kbd_is_on_hold;
7186 }
7187
7188 \f
7189 /* Enumeration of and access to system processes a-la ps(1). */
7190
7191 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7192 0, 0, 0,
7193 doc: /* Return a list of numerical process IDs of all running processes.
7194 If this functionality is unsupported, return nil.
7195
7196 See `process-attributes' for getting attributes of a process given its ID. */)
7197 (void)
7198 {
7199 return list_system_processes ();
7200 }
7201
7202 DEFUN ("process-attributes", Fprocess_attributes,
7203 Sprocess_attributes, 1, 1, 0,
7204 doc: /* Return attributes of the process given by its PID, a number.
7205
7206 Value is an alist where each element is a cons cell of the form
7207
7208 \(KEY . VALUE)
7209
7210 If this functionality is unsupported, the value is nil.
7211
7212 See `list-system-processes' for getting a list of all process IDs.
7213
7214 The KEYs of the attributes that this function may return are listed
7215 below, together with the type of the associated VALUE (in parentheses).
7216 Not all platforms support all of these attributes; unsupported
7217 attributes will not appear in the returned alist.
7218 Unless explicitly indicated otherwise, numbers can have either
7219 integer or floating point values.
7220
7221 euid -- Effective user User ID of the process (number)
7222 user -- User name corresponding to euid (string)
7223 egid -- Effective user Group ID of the process (number)
7224 group -- Group name corresponding to egid (string)
7225 comm -- Command name (executable name only) (string)
7226 state -- Process state code, such as "S", "R", or "T" (string)
7227 ppid -- Parent process ID (number)
7228 pgrp -- Process group ID (number)
7229 sess -- Session ID, i.e. process ID of session leader (number)
7230 ttname -- Controlling tty name (string)
7231 tpgid -- ID of foreground process group on the process's tty (number)
7232 minflt -- number of minor page faults (number)
7233 majflt -- number of major page faults (number)
7234 cminflt -- cumulative number of minor page faults (number)
7235 cmajflt -- cumulative number of major page faults (number)
7236 utime -- user time used by the process, in the (HIGH LOW USEC) format
7237 stime -- system time used by the process, in the (HIGH LOW USEC) format
7238 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7239 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7240 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7241 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7242 pri -- priority of the process (number)
7243 nice -- nice value of the process (number)
7244 thcount -- process thread count (number)
7245 start -- time the process started, in the (HIGH LOW USEC) format
7246 vsize -- virtual memory size of the process in KB's (number)
7247 rss -- resident set size of the process in KB's (number)
7248 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7249 pcpu -- percents of CPU time used by the process (floating-point number)
7250 pmem -- percents of total physical memory used by process's resident set
7251 (floating-point number)
7252 args -- command line which invoked the process (string). */)
7253 ( Lisp_Object pid)
7254 {
7255 return system_process_attributes (pid);
7256 }
7257
7258 \f
7259 void
7260 init_process (void)
7261 {
7262 #ifdef subprocesses
7263 register int i;
7264
7265 inhibit_sentinels = 0;
7266
7267 #ifdef SIGCHLD
7268 #ifndef CANNOT_DUMP
7269 if (! noninteractive || initialized)
7270 #endif
7271 signal (SIGCHLD, sigchld_handler);
7272 #endif
7273
7274 FD_ZERO (&input_wait_mask);
7275 FD_ZERO (&non_keyboard_wait_mask);
7276 FD_ZERO (&non_process_wait_mask);
7277 max_process_desc = 0;
7278
7279 #ifdef NON_BLOCKING_CONNECT
7280 FD_ZERO (&connect_wait_mask);
7281 num_pending_connects = 0;
7282 #endif
7283
7284 #ifdef ADAPTIVE_READ_BUFFERING
7285 process_output_delay_count = 0;
7286 process_output_skip = 0;
7287 #endif
7288
7289 /* Don't do this, it caused infinite select loops. The display
7290 method should call add_keyboard_wait_descriptor on stdin if it
7291 needs that. */
7292 #if 0
7293 FD_SET (0, &input_wait_mask);
7294 #endif
7295
7296 Vprocess_alist = Qnil;
7297 #ifdef SIGCHLD
7298 deleted_pid_list = Qnil;
7299 #endif
7300 for (i = 0; i < MAXDESC; i++)
7301 {
7302 chan_process[i] = Qnil;
7303 proc_buffered_char[i] = -1;
7304 }
7305 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7306 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7307 #ifdef DATAGRAM_SOCKETS
7308 memset (datagram_address, 0, sizeof datagram_address);
7309 #endif
7310
7311 {
7312 Lisp_Object subfeatures = Qnil;
7313 const struct socket_options *sopt;
7314
7315 #define ADD_SUBFEATURE(key, val) \
7316 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7317
7318 #ifdef NON_BLOCKING_CONNECT
7319 ADD_SUBFEATURE (QCnowait, Qt);
7320 #endif
7321 #ifdef DATAGRAM_SOCKETS
7322 ADD_SUBFEATURE (QCtype, Qdatagram);
7323 #endif
7324 #ifdef HAVE_SEQPACKET
7325 ADD_SUBFEATURE (QCtype, Qseqpacket);
7326 #endif
7327 #ifdef HAVE_LOCAL_SOCKETS
7328 ADD_SUBFEATURE (QCfamily, Qlocal);
7329 #endif
7330 ADD_SUBFEATURE (QCfamily, Qipv4);
7331 #ifdef AF_INET6
7332 ADD_SUBFEATURE (QCfamily, Qipv6);
7333 #endif
7334 #ifdef HAVE_GETSOCKNAME
7335 ADD_SUBFEATURE (QCservice, Qt);
7336 #endif
7337 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7338 ADD_SUBFEATURE (QCserver, Qt);
7339 #endif
7340
7341 for (sopt = socket_options; sopt->name; sopt++)
7342 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7343
7344 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7345 }
7346
7347 #if defined (DARWIN_OS)
7348 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7349 processes. As such, we only change the default value. */
7350 if (initialized)
7351 {
7352 const char *release = get_operating_system_release ();
7353 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7354 && release[1] == '.')) {
7355 Vprocess_connection_type = Qnil;
7356 }
7357 }
7358 #endif
7359 #endif /* subprocesses */
7360 kbd_is_on_hold = 0;
7361 }
7362
7363 void
7364 syms_of_process (void)
7365 {
7366 #ifdef subprocesses
7367
7368 Qprocessp = intern_c_string ("processp");
7369 staticpro (&Qprocessp);
7370 Qrun = intern_c_string ("run");
7371 staticpro (&Qrun);
7372 Qstop = intern_c_string ("stop");
7373 staticpro (&Qstop);
7374 Qsignal = intern_c_string ("signal");
7375 staticpro (&Qsignal);
7376
7377 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7378 here again.
7379
7380 Qexit = intern_c_string ("exit");
7381 staticpro (&Qexit); */
7382
7383 Qopen = intern_c_string ("open");
7384 staticpro (&Qopen);
7385 Qclosed = intern_c_string ("closed");
7386 staticpro (&Qclosed);
7387 Qconnect = intern_c_string ("connect");
7388 staticpro (&Qconnect);
7389 Qfailed = intern_c_string ("failed");
7390 staticpro (&Qfailed);
7391 Qlisten = intern_c_string ("listen");
7392 staticpro (&Qlisten);
7393 Qlocal = intern_c_string ("local");
7394 staticpro (&Qlocal);
7395 Qipv4 = intern_c_string ("ipv4");
7396 staticpro (&Qipv4);
7397 #ifdef AF_INET6
7398 Qipv6 = intern_c_string ("ipv6");
7399 staticpro (&Qipv6);
7400 #endif
7401 Qdatagram = intern_c_string ("datagram");
7402 staticpro (&Qdatagram);
7403 Qseqpacket = intern_c_string ("seqpacket");
7404 staticpro (&Qseqpacket);
7405
7406 QCport = intern_c_string (":port");
7407 staticpro (&QCport);
7408 QCspeed = intern_c_string (":speed");
7409 staticpro (&QCspeed);
7410 QCprocess = intern_c_string (":process");
7411 staticpro (&QCprocess);
7412
7413 QCbytesize = intern_c_string (":bytesize");
7414 staticpro (&QCbytesize);
7415 QCstopbits = intern_c_string (":stopbits");
7416 staticpro (&QCstopbits);
7417 QCparity = intern_c_string (":parity");
7418 staticpro (&QCparity);
7419 Qodd = intern_c_string ("odd");
7420 staticpro (&Qodd);
7421 Qeven = intern_c_string ("even");
7422 staticpro (&Qeven);
7423 QCflowcontrol = intern_c_string (":flowcontrol");
7424 staticpro (&QCflowcontrol);
7425 Qhw = intern_c_string ("hw");
7426 staticpro (&Qhw);
7427 Qsw = intern_c_string ("sw");
7428 staticpro (&Qsw);
7429 QCsummary = intern_c_string (":summary");
7430 staticpro (&QCsummary);
7431
7432 Qreal = intern_c_string ("real");
7433 staticpro (&Qreal);
7434 Qnetwork = intern_c_string ("network");
7435 staticpro (&Qnetwork);
7436 Qserial = intern_c_string ("serial");
7437 staticpro (&Qserial);
7438 QCbuffer = intern_c_string (":buffer");
7439 staticpro (&QCbuffer);
7440 QChost = intern_c_string (":host");
7441 staticpro (&QChost);
7442 QCservice = intern_c_string (":service");
7443 staticpro (&QCservice);
7444 QClocal = intern_c_string (":local");
7445 staticpro (&QClocal);
7446 QCremote = intern_c_string (":remote");
7447 staticpro (&QCremote);
7448 QCcoding = intern_c_string (":coding");
7449 staticpro (&QCcoding);
7450 QCserver = intern_c_string (":server");
7451 staticpro (&QCserver);
7452 QCnowait = intern_c_string (":nowait");
7453 staticpro (&QCnowait);
7454 QCsentinel = intern_c_string (":sentinel");
7455 staticpro (&QCsentinel);
7456 QClog = intern_c_string (":log");
7457 staticpro (&QClog);
7458 QCnoquery = intern_c_string (":noquery");
7459 staticpro (&QCnoquery);
7460 QCstop = intern_c_string (":stop");
7461 staticpro (&QCstop);
7462 QCoptions = intern_c_string (":options");
7463 staticpro (&QCoptions);
7464 QCplist = intern_c_string (":plist");
7465 staticpro (&QCplist);
7466
7467 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7468 staticpro (&Qlast_nonmenu_event);
7469
7470 staticpro (&Vprocess_alist);
7471 #ifdef SIGCHLD
7472 staticpro (&deleted_pid_list);
7473 #endif
7474
7475 #endif /* subprocesses */
7476
7477 QCname = intern_c_string (":name");
7478 staticpro (&QCname);
7479 QCtype = intern_c_string (":type");
7480 staticpro (&QCtype);
7481
7482 Qeuid = intern_c_string ("euid");
7483 staticpro (&Qeuid);
7484 Qegid = intern_c_string ("egid");
7485 staticpro (&Qegid);
7486 Quser = intern_c_string ("user");
7487 staticpro (&Quser);
7488 Qgroup = intern_c_string ("group");
7489 staticpro (&Qgroup);
7490 Qcomm = intern_c_string ("comm");
7491 staticpro (&Qcomm);
7492 Qstate = intern_c_string ("state");
7493 staticpro (&Qstate);
7494 Qppid = intern_c_string ("ppid");
7495 staticpro (&Qppid);
7496 Qpgrp = intern_c_string ("pgrp");
7497 staticpro (&Qpgrp);
7498 Qsess = intern_c_string ("sess");
7499 staticpro (&Qsess);
7500 Qttname = intern_c_string ("ttname");
7501 staticpro (&Qttname);
7502 Qtpgid = intern_c_string ("tpgid");
7503 staticpro (&Qtpgid);
7504 Qminflt = intern_c_string ("minflt");
7505 staticpro (&Qminflt);
7506 Qmajflt = intern_c_string ("majflt");
7507 staticpro (&Qmajflt);
7508 Qcminflt = intern_c_string ("cminflt");
7509 staticpro (&Qcminflt);
7510 Qcmajflt = intern_c_string ("cmajflt");
7511 staticpro (&Qcmajflt);
7512 Qutime = intern_c_string ("utime");
7513 staticpro (&Qutime);
7514 Qstime = intern_c_string ("stime");
7515 staticpro (&Qstime);
7516 Qtime = intern_c_string ("time");
7517 staticpro (&Qtime);
7518 Qcutime = intern_c_string ("cutime");
7519 staticpro (&Qcutime);
7520 Qcstime = intern_c_string ("cstime");
7521 staticpro (&Qcstime);
7522 Qctime = intern_c_string ("ctime");
7523 staticpro (&Qctime);
7524 Qpri = intern_c_string ("pri");
7525 staticpro (&Qpri);
7526 Qnice = intern_c_string ("nice");
7527 staticpro (&Qnice);
7528 Qthcount = intern_c_string ("thcount");
7529 staticpro (&Qthcount);
7530 Qstart = intern_c_string ("start");
7531 staticpro (&Qstart);
7532 Qvsize = intern_c_string ("vsize");
7533 staticpro (&Qvsize);
7534 Qrss = intern_c_string ("rss");
7535 staticpro (&Qrss);
7536 Qetime = intern_c_string ("etime");
7537 staticpro (&Qetime);
7538 Qpcpu = intern_c_string ("pcpu");
7539 staticpro (&Qpcpu);
7540 Qpmem = intern_c_string ("pmem");
7541 staticpro (&Qpmem);
7542 Qargs = intern_c_string ("args");
7543 staticpro (&Qargs);
7544
7545 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7546 doc: /* *Non-nil means delete processes immediately when they exit.
7547 A value of nil means don't delete them until `list-processes' is run. */);
7548
7549 delete_exited_processes = 1;
7550
7551 #ifdef subprocesses
7552 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7553 doc: /* Control type of device used to communicate with subprocesses.
7554 Values are nil to use a pipe, or t or `pty' to use a pty.
7555 The value has no effect if the system has no ptys or if all ptys are busy:
7556 then a pipe is used in any case.
7557 The value takes effect when `start-process' is called. */);
7558 Vprocess_connection_type = Qt;
7559
7560 #ifdef ADAPTIVE_READ_BUFFERING
7561 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7562 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7563 On some systems, when Emacs reads the output from a subprocess, the output data
7564 is read in very small blocks, potentially resulting in very poor performance.
7565 This behavior can be remedied to some extent by setting this variable to a
7566 non-nil value, as it will automatically delay reading from such processes, to
7567 allow them to produce more output before Emacs tries to read it.
7568 If the value is t, the delay is reset after each write to the process; any other
7569 non-nil value means that the delay is not reset on write.
7570 The variable takes effect when `start-process' is called. */);
7571 Vprocess_adaptive_read_buffering = Qt;
7572 #endif
7573
7574 defsubr (&Sprocessp);
7575 defsubr (&Sget_process);
7576 defsubr (&Sdelete_process);
7577 defsubr (&Sprocess_status);
7578 defsubr (&Sprocess_exit_status);
7579 defsubr (&Sprocess_id);
7580 defsubr (&Sprocess_name);
7581 defsubr (&Sprocess_tty_name);
7582 defsubr (&Sprocess_command);
7583 defsubr (&Sset_process_buffer);
7584 defsubr (&Sprocess_buffer);
7585 defsubr (&Sprocess_mark);
7586 defsubr (&Sset_process_filter);
7587 defsubr (&Sprocess_filter);
7588 defsubr (&Sset_process_sentinel);
7589 defsubr (&Sprocess_sentinel);
7590 defsubr (&Sset_process_window_size);
7591 defsubr (&Sset_process_inherit_coding_system_flag);
7592 defsubr (&Sset_process_query_on_exit_flag);
7593 defsubr (&Sprocess_query_on_exit_flag);
7594 defsubr (&Sprocess_contact);
7595 defsubr (&Sprocess_plist);
7596 defsubr (&Sset_process_plist);
7597 defsubr (&Slist_processes);
7598 defsubr (&Sprocess_list);
7599 defsubr (&Sstart_process);
7600 defsubr (&Sserial_process_configure);
7601 defsubr (&Smake_serial_process);
7602 defsubr (&Sset_network_process_option);
7603 defsubr (&Smake_network_process);
7604 defsubr (&Sformat_network_address);
7605 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7606 #ifdef SIOCGIFCONF
7607 defsubr (&Snetwork_interface_list);
7608 #endif
7609 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7610 defsubr (&Snetwork_interface_info);
7611 #endif
7612 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7613 #ifdef DATAGRAM_SOCKETS
7614 defsubr (&Sprocess_datagram_address);
7615 defsubr (&Sset_process_datagram_address);
7616 #endif
7617 defsubr (&Saccept_process_output);
7618 defsubr (&Sprocess_send_region);
7619 defsubr (&Sprocess_send_string);
7620 defsubr (&Sinterrupt_process);
7621 defsubr (&Skill_process);
7622 defsubr (&Squit_process);
7623 defsubr (&Sstop_process);
7624 defsubr (&Scontinue_process);
7625 defsubr (&Sprocess_running_child_p);
7626 defsubr (&Sprocess_send_eof);
7627 defsubr (&Ssignal_process);
7628 defsubr (&Swaiting_for_user_input_p);
7629 defsubr (&Sprocess_type);
7630 defsubr (&Sset_process_coding_system);
7631 defsubr (&Sprocess_coding_system);
7632 defsubr (&Sset_process_filter_multibyte);
7633 defsubr (&Sprocess_filter_multibyte_p);
7634
7635 #endif /* subprocesses */
7636
7637 defsubr (&Sget_buffer_process);
7638 defsubr (&Sprocess_inherit_coding_system_flag);
7639 defsubr (&Slist_system_processes);
7640 defsubr (&Sprocess_attributes);
7641 }
7642
7643 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7644 (do not change this comment) */